Repository navigation
Expand file tree
/
Copy pathSvgHelper.cs
More file actions
402 lines (348 loc) · 12.5 KB
/
Copy pathSvgHelper.cs
File metadata and controls
402 lines (348 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Numerics;
using System.Xml.Linq;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using Color = SixLabors.ImageSharp.Color;
using Path = SixLabors.ImageSharp.Drawing.Path;
using SolidBrush = SixLabors.ImageSharp.Drawing.Processing.SolidBrush;
namespace SixLabors.Samples.WebGPUExternalSurfaceDemo;
/// <summary>
/// Shared SVG parsing and ImageSharp element construction for SVG rendering samples.
/// </summary>
internal static class SvgHelper
{
/// <summary>
/// A single parsed SVG path element with fill, stroke, and per-element transform.
/// </summary>
internal readonly struct SvgElement
{
public SvgElement(
string pathData,
Color fill,
Color stroke,
float strokeWidth,
Matrix4x4? transform)
{
this.PathData = pathData;
this.Fill = fill;
this.Stroke = stroke;
this.StrokeWidth = strokeWidth;
this.Transform = transform;
}
public string PathData { get; }
public Color Fill { get; }
public Color Stroke { get; }
public float StrokeWidth { get; }
public Matrix4x4? Transform { get; }
}
/// <summary>
/// Parses an SVG file into a list of <see cref="SvgElement"/>s.
/// Handles fill, fill-opacity, stroke, stroke-width, opacity, and per-path transform attributes.
/// Group-level transforms are composed with per-path transforms.
/// </summary>
public static List<SvgElement> ParseSvg(string filePath)
{
XDocument doc = XDocument.Load(filePath);
XNamespace ns = "http://www.w3.org/2000/svg";
List<SvgElement> result = [];
// Collect group transforms into a stack.
// For simplicity, iterate all path elements and walk up to resolve inherited transforms.
foreach (XElement pathEl in doc.Descendants(ns + "path"))
{
string? d = pathEl.Attribute("d")?.Value;
if (string.IsNullOrWhiteSpace(d))
{
continue;
}
// Parse fill color (default black per SVG spec).
string? fillStr = ResolveInheritedPresentationValue(pathEl, "fill");
Color fill;
if (fillStr is null)
{
fill = Color.Black;
}
else if (fillStr == "none")
{
fill = Color.Transparent;
}
else if (Color.TryParse(fillStr, out Color parsed))
{
fill = parsed;
}
else
{
fill = Color.Black;
}
// Apply fill-opacity.
if (float.TryParse(
ResolveInheritedPresentationValue(pathEl, "fill-opacity"),
NumberStyles.Float,
CultureInfo.InvariantCulture,
out float fillOpacity))
{
Rgba32 fp = fill.ToPixel<Rgba32>();
fp.A = (byte)(fp.A * Math.Clamp(fillOpacity, 0f, 1f));
fill = Color.FromPixel(fp);
}
// Apply element-level opacity to fill alpha.
if (float.TryParse(
pathEl.Attribute("opacity")?.Value,
NumberStyles.Float,
CultureInfo.InvariantCulture,
out float opacity))
{
Rgba32 fp = fill.ToPixel<Rgba32>();
fp.A = (byte)(fp.A * Math.Clamp(opacity, 0f, 1f));
fill = Color.FromPixel(fp);
}
// Parse stroke.
Color stroke = ParseColor(ResolveInheritedPresentationValue(pathEl, "stroke"));
float strokeWidth = float.TryParse(
ResolveInheritedPresentationValue(pathEl, "stroke-width"),
NumberStyles.Float,
CultureInfo.InvariantCulture,
out float sw) ? sw : 0f;
// Apply element-level opacity to stroke alpha.
if (opacity is > 0 and < 1)
{
Rgba32 sp = stroke.ToPixel<Rgba32>();
sp.A = (byte)(sp.A * Math.Clamp(opacity, 0f, 1f));
stroke = Color.FromPixel(sp);
}
// Resolve transform: compose per-path transform with ancestor group transforms.
Matrix4x4? transform = ResolveTransform(pathEl, ns);
result.Add(new SvgElement(d, fill, stroke, strokeWidth, transform));
}
return result;
}
/// <summary>
/// Builds pre-parsed ImageSharp elements for benchmarking.
/// </summary>
public static List<(IPath Path, SolidBrush? Fill, SolidPen? Stroke)> BuildImageSharpElements(
List<SvgElement> elements,
float scale)
{
List<(IPath, SolidBrush?, SolidPen?)> result = [];
foreach (SvgElement el in elements)
{
if (!Path.TryParseSvgPath(el.PathData, out IPath? isPath))
{
continue;
}
Matrix4x4 scaleMatrix = Matrix4x4.CreateScale(scale, scale, 1);
if (el.Transform.HasValue)
{
isPath = isPath.Transform(el.Transform.Value * scaleMatrix);
}
else
{
isPath = isPath.Transform(scaleMatrix);
}
Rgba32 fillPixel = el.Fill.ToPixel<Rgba32>();
SolidBrush? fill = fillPixel.A > 0
? new SolidBrush(el.Fill)
: null;
Rgba32 strokePixel = el.Stroke.ToPixel<Rgba32>();
SolidPen? stroke = strokePixel.A > 0 && el.StrokeWidth > 0
? new SolidPen(el.Stroke, el.StrokeWidth * scale)
: null;
result.Add((isPath, fill, stroke));
}
return result;
}
// ---- SVG transform resolution ----
private static Matrix4x4? ResolveTransform(XElement element, XNamespace ns)
{
// Walk up the tree, collecting transforms from path → root.
List<Matrix4x4>? transforms = null;
XElement? current = element;
while (current is not null)
{
string? transformStr = current.Attribute("transform")?.Value;
if (transformStr is not null && TryParseTransform(transformStr, out Matrix4x4 m))
{
transforms ??= [];
transforms.Add(m);
}
current = current?.Parent;
}
if (transforms is null)
{
return null;
}
// Compose from root → leaf (reverse of collection order).
Matrix4x4 result = Matrix4x4.Identity;
for (int i = transforms.Count - 1; i >= 0; i--)
{
result *= transforms[i];
}
return result;
}
private static bool TryParseTransform(string value, out Matrix4x4 result)
{
result = Matrix4x4.Identity;
ReadOnlySpan<char> span = value.AsSpan().Trim();
if (span.StartsWith("matrix(") && span.EndsWith(")"))
{
span = span[7..^1];
Span<float> values = stackalloc float[6];
for (int i = 0; i < 6; i++)
{
span = span.TrimStart();
if (span.Length > 0 && span[0] == ',')
{
span = span[1..].TrimStart();
}
int end = 0;
if (end < span.Length && (span[end] is '-' or '+'))
{
end++;
}
bool hasDot = false;
while (end < span.Length)
{
char c = span[end];
if (c == '.' && !hasDot)
{
hasDot = true;
end++;
}
else if (char.IsDigit(c))
{
end++;
}
else if (c is 'e' or 'E')
{
end++;
if (end < span.Length && span[end] is '+' or '-')
{
end++;
}
while (end < span.Length && char.IsDigit(span[end]))
{
end++;
}
break;
}
else
{
break;
}
}
if (end == 0)
{
return false;
}
values[i] = float.Parse(span[..end], CultureInfo.InvariantCulture);
span = span[end..];
}
// SVG matrix(a,b,c,d,e,f) maps to:
// | a c e | M11=a M21=c M41=e
// | b d f | → M12=b M22=d M42=f
// | 0 0 1 | rest = identity
result = new Matrix4x4(
values[0],
values[1],
0,
0,
values[2],
values[3],
0,
0,
0,
0,
1,
0,
values[4],
values[5],
0,
1);
return true;
}
if (span.StartsWith("translate(") && span.EndsWith(")"))
{
span = span[10..^1];
ReadOnlySpan<char> trimmed = span.Trim();
int sep = trimmed.IndexOfAny(',', ' ');
float tx = float.Parse(sep < 0 ? trimmed : trimmed[..sep], CultureInfo.InvariantCulture);
float ty = sep < 0 ? 0 : float.Parse(trimmed[(sep + 1)..].Trim(), CultureInfo.InvariantCulture);
result = Matrix4x4.CreateTranslation(tx, ty, 0);
return true;
}
if (span.StartsWith("scale(") && span.EndsWith(")"))
{
span = span[6..^1];
ReadOnlySpan<char> trimmed = span.Trim();
int sep = trimmed.IndexOfAny(',', ' ');
float sx = float.Parse(sep < 0 ? trimmed : trimmed[..sep], CultureInfo.InvariantCulture);
float sy = sep < 0 ? sx : float.Parse(trimmed[(sep + 1)..].Trim(), CultureInfo.InvariantCulture);
result = Matrix4x4.CreateScale(sx, sy, 1);
return true;
}
return false;
}
private static Color ParseColor(string? value)
{
if (string.IsNullOrWhiteSpace(value) || value == "none")
{
return Color.Transparent;
}
return Color.TryParse(value, out Color color) ? color : Color.Transparent;
}
private static string? ResolveInheritedPresentationValue(XElement element, string attributeName)
{
for (XElement? current = element; current is not null; current = current?.Parent)
{
if (TryGetPresentationValue(current, attributeName, out string? value))
{
return value;
}
}
return null;
}
private static bool TryGetPresentationValue(XElement element, string attributeName, [NotNullWhen(true)] out string? value)
{
XAttribute? attribute = element.Attribute(attributeName);
if (attribute is not null)
{
value = attribute.Value;
return true;
}
string? style = element.Attribute("style")?.Value;
if (TryGetStyleValue(style, attributeName, out value))
{
return true;
}
value = null;
return false;
}
private static bool TryGetStyleValue(string? style, string attributeName, [NotNullWhen(true)] out string? value)
{
if (string.IsNullOrWhiteSpace(style))
{
value = null;
return false;
}
foreach (string entry in style.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
int separatorIndex = entry.IndexOf(':');
if (separatorIndex <= 0 || separatorIndex >= entry.Length - 1)
{
continue;
}
if (!entry[..separatorIndex].Equals(attributeName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
value = entry[(separatorIndex + 1)..].Trim();
return true;
}
value = null;
return false;
}
}