Skip to content

Commit c37c70d

Browse files
Merge pull request #432 from SixLabors/js/v3-issue-430-dashed-ellipse
[V3] Preserve gaps in dashed ellipse strokes
2 parents a631c96 + dc53954 commit c37c70d

46 files changed

Lines changed: 120 additions & 116 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,3 +234,6 @@ SixLabors.Shapes.Coverage.xml
234234
/plans/
235235

236236
samples/Avalonia**
237+
238+
# Local specifications
239+
specs/

‎src/ImageSharp.Drawing.WebGPU/WebGPUSceneEncoder.cs‎

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3429,7 +3429,7 @@ private void AppendPlainStroke(
34293429
GpuSceneDrawMonoid drawTagMonoid = GpuSceneDrawTag.Map(drawTag);
34303430
Rectangle interestBounds = ToTargetLocal(command.RasterizerOptions.Interest, this.rootTargetBounds);
34313431
(uint style0, uint style1, uint style2, uint style3, uint style4, uint style5, uint style6, uint style7, uint style8, uint style9) =
3432-
GetStrokeStyle(command.GraphicsOptions, pen, widthScale, interestBounds);
3432+
GetStrokeStyle(command.GraphicsOptions, pen, widthScale, interestBounds, command.RasterizerOptions.CoverageBoost);
34333433
int pathTagCheckpoint = this.PathTags.Count;
34343434
int styleCheckpoint = this.Styles.Count;
34353435
bool appendStyle = !this.hasLastStyle ||
@@ -3572,7 +3572,7 @@ private void AppendExplicitStroke(
35723572
GpuSceneDrawMonoid drawTagMonoid = GpuSceneDrawTag.Map(drawTag);
35733573
Rectangle interestBounds = ToTargetLocal(rasterizerOptions.Interest, this.rootTargetBounds);
35743574
(uint style0, uint style1, uint style2, uint style3, uint style4, uint style5, uint style6, uint style7, uint style8, uint style9) =
3575-
GetStrokeStyle(graphicsOptions, pen, widthScale, interestBounds);
3575+
GetStrokeStyle(graphicsOptions, pen, widthScale, interestBounds, rasterizerOptions.CoverageBoost);
35763576
int pathTagCheckpoint = this.PathTags.Count;
35773577
int styleCheckpoint = this.Styles.Count;
35783578
bool appendStyle = !this.hasLastStyle ||
@@ -3711,7 +3711,7 @@ private void AppendExplicitStroke(
37113711
GpuSceneDrawMonoid drawTagMonoid = GpuSceneDrawTag.Map(drawTag);
37123712
Rectangle interestBounds = ToTargetLocal(rasterizerOptions.Interest, this.rootTargetBounds);
37133713
(uint style0, uint style1, uint style2, uint style3, uint style4, uint style5, uint style6, uint style7, uint style8, uint style9) =
3714-
GetStrokeStyle(graphicsOptions, pen, widthScale, interestBounds);
3714+
GetStrokeStyle(graphicsOptions, pen, widthScale, interestBounds, rasterizerOptions.CoverageBoost);
37153715
int pathTagCheckpoint = this.PathTags.Count;
37163716
int styleCheckpoint = this.Styles.Count;
37173717
bool appendStyle = !this.hasLastStyle ||
@@ -7561,17 +7561,9 @@ private static int EncodeStrokePath(
75617561

75627562
int segmentCount = keptCount - 1;
75637563

7564-
// Match the CPU closure rule. A contour with at least three source points is closed
7565-
// when it is declared closed or its endpoints are within one scaled stroke width.
7566-
bool isClosed = false;
7567-
if (contourPoints.Length >= 3)
7568-
{
7569-
PointF last = contourPoints[^1];
7570-
float closeThreshold = MathF.Max(strokeWidth, 1E-3F);
7571-
isClosed = contour.IsClosed ||
7572-
firstPoint == last ||
7573-
Vector2.DistanceSquared(firstPoint, last) <= closeThreshold * closeThreshold;
7574-
}
7564+
// An open path with a gap needs caps, even when the gap is shorter than the stroke width.
7565+
bool isClosed = contourPoints.Length >= 3 &&
7566+
(contour.IsClosed || firstPoint == contourPoints[^1]);
75757567

75767568
bool duplicateClosingPoint = keptCount > 1 && lastKept == firstPoint;
75777569
int distinctPointCount = keptCount - (isClosed && duplicateClosingPoint ? 1 : 0);
@@ -8774,9 +8766,8 @@ private static void AppendIdentityTransform(ref OwnedStream<uint> transforms)
87748766
/// </summary>
87758767
/// <remarks>
87768768
/// Word layout consumed by path_lowering.wgsl: 0 = style flags, 1 = device-space stroke width,
8777-
/// 2 = packed draw flags, 3 = miter limit, 4 = arc detail scale, 5 = zero,
8769+
/// 2 = packed draw flags, 3 = miter limit, 4 = arc detail scale, 5 = coverage boost,
87788770
/// 6-9 = target-local interest rectangle as left, top, right, bottom.
8779-
/// Strokes do not use antialiased text coverage boost data, so word 5 is zero in both modes.
87808771
/// <para>
87818772
/// Bits 0-10 of word 0 hold the arc limit: the interior vertex count of a round arc of
87828773
/// half a turn, from <see cref="GetStrokeArcLineCost"/>. The shader clamps the vertex count of
@@ -8789,6 +8780,7 @@ private static void AppendIdentityTransform(ref OwnedStream<uint> transforms)
87898780
/// <param name="pen">The pen that defines stroke width, joins, caps, and miter limit.</param>
87908781
/// <param name="widthScale">The transform-derived scale applied to the stroke width.</param>
87918782
/// <param name="interestBounds">The target-local raster interest bounds.</param>
8783+
/// <param name="coverageBoost">The coverage boost for antialiased text strokes.</param>
87928784
/// <returns>The ten packed style words.</returns>
87938785
[MethodImpl(MethodImplOptions.AggressiveInlining)]
87948786
private static (
@@ -8805,7 +8797,8 @@ private static (
88058797
GraphicsOptions options,
88068798
Pen pen,
88078799
float widthScale,
8808-
Rectangle interestBounds)
8800+
Rectangle interestBounds,
8801+
float coverageBoost)
88098802
{
88108803
StyleFlags styleFlags = StyleFlags.Stroke
88118804
| EncodeStrokeJoinFlags(pen.StrokeOptions.LineJoin)
@@ -8825,7 +8818,7 @@ private static (
88258818
PackStyleDrawFlags(options),
88268819
BitcastSingle((float)pen.StrokeOptions.MiterLimit),
88278820
BitcastSingle((float)pen.StrokeOptions.ArcDetailScale),
8828-
0U,
8821+
options.Antialias ? BitcastSingle(coverageBoost) : 0U,
88298822
BitcastSingle(interestBounds.Left),
88308823
BitcastSingle(interestBounds.Top),
88318824
BitcastSingle(interestBounds.Right),

‎src/ImageSharp.Drawing/ImageSharp.Drawing.csproj‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
<ItemGroup>
4747
<PackageReference Include="SixLabors.Fonts" Version="3.2.0" />
4848
<PackageReference Include="SixLabors.ImageSharp" Version="4.1.3" />
49-
<PackageReference Include="SixLabors.PolygonClipper" Version="1.0.2" />
49+
<PackageReference Include="SixLabors.PolygonClipper" Version="1.0.3" />
5050
</ItemGroup>
5151

5252
<!--

‎src/ImageSharp.Drawing/PolygonGeometry/StrokedShapeGenerator.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ private static PolygonClipper.StrokeOptions CreateStrokeOptions(StrokeOptions op
8080
{
8181
PolygonClipper.StrokeOptions o = new()
8282
{
83+
// The conversion marks closed paths with a repeated start point.
84+
CloseNearEndpoints = false,
8385
ArcDetailScale = options.ArcDetailScale,
8486
MiterLimit = options.MiterLimit,
8587
LineJoin = options.LineJoin switch

‎src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.Stroke.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ private static StrokeRasterizableGeometry CreateRetainedStrokeRasterizableGeomet
383383
bandTop,
384384
options.IntersectionRule,
385385
options.RasterizationMode,
386-
coverageBoost: 0F,
386+
options.CoverageBoost,
387387
hasStartCovers,
388388
options.Interest);
389389
}
@@ -454,7 +454,7 @@ private static StrokeRasterizableGeometry CreateRetainedStrokeRasterizableGeomet
454454
bandTop,
455455
options.IntersectionRule,
456456
options.RasterizationMode,
457-
coverageBoost: 0F,
457+
options.CoverageBoost,
458458
hasStartCovers,
459459
options.Interest);
460460
}

‎src/ImageSharp.Drawing/Processing/Backends/DefaultRasterizer.StrokeLinearizer.cs‎

Lines changed: 3 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,9 @@ protected override bool ProcessCore()
106106
continue;
107107
}
108108

109-
bool isClosed = this.IsContourClosedForEmission(contourPoints, contour.IsClosed);
109+
// An open path with a gap needs caps, even when the gap is shorter than the stroke width.
110+
bool isClosed = contourPoints.Length >= 3 &&
111+
(contour.IsClosed || contourPoints[0] == contourPoints[^1]);
110112

111113
this.ProcessContour(contourPoints, isClosed, contourInterest == ContourInterest.Contained);
112114
}
@@ -149,47 +151,6 @@ private ContourInterest GetContourInterest(ReadOnlySpan<PointF> contourPoints)
149151
return ContourInterest.Clipped;
150152
}
151153

152-
/// <summary>
153-
/// Returns whether a contour should be treated as closed when emitting stroke geometry.
154-
/// A contour is closed when it is declared closed, its first and last points coincide, or
155-
/// the endpoint gap is at most max(strokeWidth, 1e-3). Mirrored at encode time by
156-
/// <c>WebGPUSceneEncoder.EncodeStrokePath</c>; both must stay in lockstep.
157-
/// </summary>
158-
/// <param name="contourPoints">The contour points.</param>
159-
/// <param name="isDeclaredClosed">Indicates whether the contour is explicitly closed.</param>
160-
/// <returns><see langword="true"/> when the contour should be stroked as closed; otherwise <see langword="false"/>.</returns>
161-
private bool IsContourClosedForEmission(ReadOnlySpan<PointF> contourPoints, bool isDeclaredClosed)
162-
{
163-
// Fewer than three points cannot enclose area, so such contours always stroke open.
164-
if (contourPoints.Length < 3)
165-
{
166-
return false;
167-
}
168-
169-
PointF first = this.TransformPoint(contourPoints[0]);
170-
PointF last = this.TransformPoint(contourPoints[^1]);
171-
172-
if (isDeclaredClosed || first == last)
173-
{
174-
return true;
175-
}
176-
177-
// Near-closure: a gap no wider than the stroke itself is visually sealed by the
178-
// stroke body, so emit a wrap join instead of two caps facing across a slit.
179-
Vector2 delta = first - last;
180-
float closeThreshold = MathF.Max(this.stroke.Width, 1E-3F);
181-
return delta.LengthSquared() <= closeThreshold * closeThreshold;
182-
}
183-
184-
/// <summary>
185-
/// Applies the residual transform to one source point when one is present.
186-
/// </summary>
187-
/// <param name="point">The source point.</param>
188-
/// <returns>The transformed point.</returns>
189-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
190-
private PointF TransformPoint(PointF point)
191-
=> this.HasResidual ? PointF.Transform(point, this.Residual) : point;
192-
193154
/// <summary>
194155
/// Processes one centerline contour.
195156
/// </summary>

‎tests/ImageSharp.Drawing.Tests/Processing/Backends/WebGPUDrawingBackendTests.cs‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1986,6 +1986,46 @@ void DrawAction(DrawingCanvas canvas)
19861986
AssertBackendPairReferenceOutputs(provider, null, defaultImage, nativeSurfaceImage);
19871987
}
19881988

1989+
/// <summary>
1990+
/// Checks the dash pattern on the full ellipse from issue 430.
1991+
/// </summary>
1992+
/// <typeparam name="TPixel">The pixel format.</typeparam>
1993+
/// <param name="provider">The white test image.</param>
1994+
[WebGPUTheory]
1995+
[WithSolidFilledImages(256, 256, "White", PixelTypes.Rgba32)]
1996+
public void DrawPath_MiterDashedEllipse_PreservesGaps<TPixel>(TestImageProvider<TPixel> provider)
1997+
where TPixel : unmanaged, IPixel<TPixel>
1998+
{
1999+
IPath ellipse = new EllipsePolygon(128, 128, 200, 200);
2000+
Pen pen = new PatternPen(new PenOptions(Color.Black, 2F, [4F, 2F, 1F, 2F])
2001+
{
2002+
StrokeOptions = new StrokeOptions { LineJoin = LineJoin.Miter, LineCap = LineCap.Butt }
2003+
});
2004+
2005+
DrawingOptions options = new();
2006+
void DrawStroke(DrawingCanvas canvas) => canvas.Draw(pen, ellipse);
2007+
2008+
using Image<TPixel> defaultImage = provider.GetImage();
2009+
RenderWithDefaultBackend(defaultImage, options, DrawStroke);
2010+
2011+
using WebGPUDrawingBackend backend = new();
2012+
using Image<TPixel> initialImage = provider.GetImage();
2013+
using Image<TPixel> nativeImage = RenderWithNativeSurfaceWebGpuBackend(
2014+
defaultImage.Width,
2015+
defaultImage.Height,
2016+
backend,
2017+
options,
2018+
DrawStroke,
2019+
initialImage);
2020+
2021+
DebugSaveBackendPair(provider, null, defaultImage, nativeImage);
2022+
2023+
// The measured difference between the CPU and WebGPU images is 0.00095%.
2024+
AssertBackendPairSimilarity(defaultImage, nativeImage, 0.002F);
2025+
2026+
AssertBackendPairReferenceOutputs(provider, null, defaultImage, nativeImage);
2027+
}
2028+
19892029
[WebGPUTheory]
19902030
[WithSolidFilledImages(256, 256, "White", PixelTypes.Rgba32, LineCap.Square)]
19912031
[WithSolidFilledImages(256, 256, "White", PixelTypes.Rgba32, LineCap.Round)]
@@ -2159,8 +2199,7 @@ public void DrawPath_StrokeImageBrushMiterJoin_MatchesDefaultOutput<TPixel>(Test
21592199
// sqrt(m^2 + 1) half widths from the corner. The centerline here turns back at (100, 112.5) by
21602200
// almost 180 degrees. For half width 5 and limit 4, the bevel then covers part of column 79,
21612201
// outside bounds that are inflated by m half widths (x = 80). Both backends must draw the bevel
2162-
// pixels of column 79. The edge pixels differ by one 8-bit level between the CPU and the GPU:
2163-
// 0.0003% measured. A bevel column that one backend cuts gives 0.0011%.
2202+
// pixels of column 79. Edge coverage differs by 0.00042% between the backends.
21642203
[WebGPUTheory]
21652204
[WithSolidFilledImages(200, 160, "White", PixelTypes.Rgba32)]
21662205
public void DrawPath_StrokeMiterJoinReversal_MatchesDefaultOutput<TPixel>(TestImageProvider<TPixel> provider)
@@ -2203,7 +2242,7 @@ public void DrawPath_StrokeMiterJoinReversal_MatchesDefaultOutput<TPixel>(TestIm
22032242
RenderWithDefaultBackend(referenceImage, drawingOptions, canvas => canvas.Fill(pen.StrokeFill, outline));
22042243

22052244
DebugSaveBackendPair(provider, null, defaultImage, nativeSurfaceImage);
2206-
AssertBackendPairSimilarity(defaultImage, nativeSurfaceImage, 0.0004F);
2245+
AssertBackendPairSimilarity(defaultImage, nativeSurfaceImage, 0.00043F);
22072246
for (int y = 0; y < referenceImage.Height; y++)
22082247
{
22092248
Assert.Equal(referenceImage[79, y], defaultImage[79, y]);
-87.6 KB
Binary file not shown.
Binary file not shown.
-4.52 MB
Binary file not shown.

0 commit comments

Comments
 (0)