-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathdata.go
More file actions
419 lines (379 loc) · 9.3 KB
/
Copy pathpathdata.go
File metadata and controls
419 lines (379 loc) · 9.3 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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package svgreader
import (
"fmt"
"strconv"
"strings"
)
// PathCommand represents a single SVG path command with its arguments.
type PathCommand struct {
Cmd byte // Command letter: M, L, H, V, C, S, Q, T, A, Z (upper=absolute, lower=relative)
Args []float64 // Coordinate arguments
}
// argsPerCommand returns the number of arguments expected for each command.
func argsPerCommand(cmd byte) int {
switch cmd | 0x20 { // lowercase
case 'z':
return 0
case 'h', 'v':
return 1
case 'm', 'l', 't':
return 2
case 's', 'q':
return 4
case 'c':
return 6
case 'a':
return 7
default:
return -1
}
}
// ParsePathData parses an SVG path data string (the "d" attribute) into a
// sequence of path commands.
//
// Supported commands: M, L, H, V, C, S, Q, T, A, Z and their relative
// (lowercase) variants. Implicit command repetition is handled: extra
// coordinate pairs after M are treated as L, and similarly for other commands.
func ParsePathData(d string) ([]PathCommand, error) {
p := pathParser{input: d}
return p.parse()
}
type pathParser struct {
input string
pos int
}
func (p *pathParser) parse() ([]PathCommand, error) {
var cmds []PathCommand
var lastCmd byte
for {
p.skipWhitespaceAndCommas()
if p.pos >= len(p.input) {
break
}
ch := p.input[p.pos]
var cmd byte
if isPathCommand(ch) {
cmd = ch
p.pos++
} else if lastCmd != 0 {
// Implicit repetition
switch lastCmd {
case 'M':
cmd = 'L'
case 'm':
cmd = 'l'
default:
cmd = lastCmd
}
} else {
return nil, fmt.Errorf("svgreader: expected command at position %d, got %q", p.pos, ch)
}
nargs := argsPerCommand(cmd)
if nargs < 0 {
return nil, fmt.Errorf("svgreader: unknown path command %q", cmd)
}
if nargs == 0 {
cmds = append(cmds, PathCommand{Cmd: cmd})
lastCmd = cmd
continue
}
// Read argument groups (command may repeat with multiple arg sets)
for {
args, err := p.readArgs(cmd, nargs)
if err != nil {
return nil, err
}
cmds = append(cmds, PathCommand{Cmd: cmd, Args: args})
lastCmd = cmd
// After first M, implicit commands become L
if cmd == 'M' {
cmd = 'L'
} else if cmd == 'm' {
cmd = 'l'
}
// Check if more numbers follow (implicit repetition)
p.skipWhitespaceAndCommas()
if p.pos >= len(p.input) {
break
}
ch := p.input[p.pos]
if isPathCommand(ch) {
break
}
if !isNumberStart(ch) {
break
}
}
}
return cmds, nil
}
// readArgs reads nargs numbers for the given command. For arc commands (A/a),
// arguments 3 and 4 are flag values (0 or 1) that may be packed without
// separators.
func (p *pathParser) readArgs(cmd byte, nargs int) ([]float64, error) {
args := make([]float64, nargs)
isArc := cmd == 'A' || cmd == 'a'
for i := range nargs {
p.skipWhitespaceAndCommas()
if isArc && (i == 3 || i == 4) {
// Arc flags: single digit 0 or 1, possibly without separator
f, err := p.readFlag()
if err != nil {
return nil, fmt.Errorf("svgreader: arc flag at position %d: %w", p.pos, err)
}
args[i] = f
} else {
n, err := p.readNumber()
if err != nil {
return nil, fmt.Errorf("svgreader: argument %d for %q at position %d: %w", i, cmd, p.pos, err)
}
args[i] = n
}
}
return args, nil
}
func (p *pathParser) readFlag() (float64, error) {
if p.pos >= len(p.input) {
return 0, fmt.Errorf("unexpected end of path data")
}
ch := p.input[p.pos]
if ch == '0' || ch == '1' {
p.pos++
return float64(ch - '0'), nil
}
return 0, fmt.Errorf("expected flag (0 or 1), got %q", ch)
}
func (p *pathParser) readNumber() (float64, error) {
if p.pos >= len(p.input) {
return 0, fmt.Errorf("unexpected end of path data")
}
start := p.pos
// Optional sign
if p.pos < len(p.input) && (p.input[p.pos] == '-' || p.input[p.pos] == '+') {
p.pos++
}
// Integer part
hadDigit := false
for p.pos < len(p.input) && p.input[p.pos] >= '0' && p.input[p.pos] <= '9' {
p.pos++
hadDigit = true
}
// Decimal part
if p.pos < len(p.input) && p.input[p.pos] == '.' {
p.pos++
for p.pos < len(p.input) && p.input[p.pos] >= '0' && p.input[p.pos] <= '9' {
p.pos++
hadDigit = true
}
}
if !hadDigit {
return 0, fmt.Errorf("expected number at position %d", start)
}
// Exponent
if p.pos < len(p.input) && (p.input[p.pos] == 'e' || p.input[p.pos] == 'E') {
p.pos++
if p.pos < len(p.input) && (p.input[p.pos] == '+' || p.input[p.pos] == '-') {
p.pos++
}
for p.pos < len(p.input) && p.input[p.pos] >= '0' && p.input[p.pos] <= '9' {
p.pos++
}
}
f, err := strconv.ParseFloat(p.input[start:p.pos], 64)
if err != nil {
return 0, fmt.Errorf("invalid number %q: %w", p.input[start:p.pos], err)
}
return f, nil
}
func (p *pathParser) skipWhitespaceAndCommas() {
for p.pos < len(p.input) {
ch := p.input[p.pos]
if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == ',' {
p.pos++
} else {
break
}
}
}
func isPathCommand(ch byte) bool {
switch ch {
case 'M', 'm', 'L', 'l', 'H', 'h', 'V', 'v',
'C', 'c', 'S', 's', 'Q', 'q', 'T', 't',
'A', 'a', 'Z', 'z':
return true
}
return false
}
func isNumberStart(ch byte) bool {
return ch == '-' || ch == '+' || ch == '.' || (ch >= '0' && ch <= '9')
}
// ResolveToAbsolute converts all relative commands to absolute coordinates.
// This simplifies rendering since PDF only uses absolute coordinates.
func ResolveToAbsolute(cmds []PathCommand) []PathCommand {
var result []PathCommand
var cx, cy float64 // current point
var sx, sy float64 // start of current subpath
for _, c := range cmds {
isRel := c.Cmd >= 'a' && c.Cmd <= 'z'
absCmd := c.Cmd
if isRel {
absCmd = c.Cmd - 32 // to uppercase
}
args := make([]float64, len(c.Args))
copy(args, c.Args)
switch absCmd {
case 'M':
if isRel {
args[0] += cx
args[1] += cy
}
cx, cy = args[0], args[1]
sx, sy = cx, cy
case 'L', 'T':
if isRel {
args[0] += cx
args[1] += cy
}
cx, cy = args[0], args[1]
case 'H':
if isRel {
args[0] += cx
}
cx = args[0]
case 'V':
if isRel {
args[0] += cy
}
cy = args[0]
case 'C':
if isRel {
for i := 0; i < 6; i += 2 {
args[i] += cx
args[i+1] += cy
}
}
cx, cy = args[4], args[5]
case 'S', 'Q':
if isRel {
for i := 0; i < 4; i += 2 {
args[i] += cx
args[i+1] += cy
}
}
cx, cy = args[len(args)-2], args[len(args)-1]
case 'A':
if isRel {
args[5] += cx
args[6] += cy
}
cx, cy = args[5], args[6]
case 'Z':
cx, cy = sx, sy
}
result = append(result, PathCommand{Cmd: absCmd, Args: args})
}
return result
}
// ExpandShorthands expands S/T shorthand commands into full C/Q commands by
// computing the reflected control point from the previous command.
func ExpandShorthands(cmds []PathCommand) []PathCommand {
var result []PathCommand
var cx, cy float64 // current point
var lastCtrlX, lastCtrlY float64 // last control point for reflection
var lastCmd byte
for _, c := range cmds {
switch c.Cmd {
case 'S':
// Smooth cubic: reflect last C control point
var rx, ry float64
if lastCmd == 'C' || lastCmd == 'S' {
rx = 2*cx - lastCtrlX
ry = 2*cy - lastCtrlY
} else {
rx, ry = cx, cy
}
result = append(result, PathCommand{
Cmd: 'C',
Args: []float64{rx, ry, c.Args[0], c.Args[1], c.Args[2], c.Args[3]},
})
lastCtrlX, lastCtrlY = c.Args[0], c.Args[1]
cx, cy = c.Args[2], c.Args[3]
case 'T':
// Smooth quadratic: reflect last Q control point
var rx, ry float64
if lastCmd == 'Q' || lastCmd == 'T' {
rx = 2*cx - lastCtrlX
ry = 2*cy - lastCtrlY
} else {
rx, ry = cx, cy
}
result = append(result, PathCommand{
Cmd: 'Q',
Args: []float64{rx, ry, c.Args[0], c.Args[1]},
})
lastCtrlX, lastCtrlY = rx, ry
cx, cy = c.Args[0], c.Args[1]
case 'C':
result = append(result, c)
lastCtrlX, lastCtrlY = c.Args[2], c.Args[3]
cx, cy = c.Args[4], c.Args[5]
case 'Q':
result = append(result, c)
lastCtrlX, lastCtrlY = c.Args[0], c.Args[1]
cx, cy = c.Args[2], c.Args[3]
case 'M':
result = append(result, c)
cx, cy = c.Args[0], c.Args[1]
lastCtrlX, lastCtrlY = cx, cy
case 'L', 'H', 'V':
result = append(result, c)
switch c.Cmd {
case 'L':
cx, cy = c.Args[0], c.Args[1]
case 'H':
cx = c.Args[0]
case 'V':
cy = c.Args[0]
}
lastCtrlX, lastCtrlY = cx, cy
default:
result = append(result, c)
if c.Cmd == 'A' && len(c.Args) >= 7 {
cx, cy = c.Args[5], c.Args[6]
}
lastCtrlX, lastCtrlY = cx, cy
}
lastCmd = c.Cmd
}
return result
}
// QuadToCubic converts a quadratic Bézier (Q) to a cubic Bézier (C).
// PDF only supports cubic Bézier curves.
func QuadToCubic(qx0, qy0, qx1, qy1, qx2, qy2 float64) (cx1, cy1, cx2, cy2 float64) {
// CP1 = Q0 + 2/3 * (Q1 - Q0)
cx1 = qx0 + 2.0/3.0*(qx1-qx0)
cy1 = qy0 + 2.0/3.0*(qy1-qy0)
// CP2 = Q2 + 2/3 * (Q1 - Q2)
cx2 = qx2 + 2.0/3.0*(qx1-qx2)
cy2 = qy2 + 2.0/3.0*(qy1-qy2)
return
}
// String returns the SVG path data string representation of the commands.
func PathCommandsToString(cmds []PathCommand) string {
var buf strings.Builder
for _, c := range cmds {
if buf.Len() > 0 {
buf.WriteByte(' ')
}
buf.WriteByte(c.Cmd)
for i, a := range c.Args {
if i > 0 {
buf.WriteByte(' ')
} else {
buf.WriteByte(' ')
}
buf.WriteString(strconv.FormatFloat(a, 'f', -1, 64))
}
}
return buf.String()
}