-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgerber.go
1087 lines (974 loc) · 26.5 KB
/
gerber.go
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package gerber provides a parser for Gerber files.
package gerber
import (
"bufio"
_ "embed"
"fmt"
"io"
"math"
"strconv"
"strings"
"github.com/pkg/errors"
)
// A Processor performs Gerber graphic operations.
// For an example implementation, visit https://pkg.go.dev/github.com/fumin/gerber/svg .
type Processor interface {
// SetDecimal sets the multiplier to convert from millimeters to Gerber units..
SetDecimal(decimal float64)
// Circle draws a circle.
Circle(lineIdx, x, y, diameter int, polarity bool)
// Rectangle draws a rectangle.
Rectangle(lineIdx, x, y, width, height int, polarity bool)
// Obround draws an obround.
Obround(lineIdx, x, y, width, height int, polarity bool)
// Contour draws a contour.
Contour(Contour) error
// Line draws a line.
Line(lineIdx, x0, y0, x1, y1, diameter int, linecap LineCap)
// Arc draws an arc.
Arc(lineIdx, xs, ys, xe, ye, xc, yc int, interpolation Interpolation, diameter int) error
// SetViewbox sets the viewbox of the Gerber image.
// It is called by the Parser when parsing has completed.
SetViewbox(minX, maxX, minY, maxY int)
}
func parseApertureID(word string) (string, error) {
if len(word) < 3 {
return "", errors.Errorf("%d", len(word))
}
if word[0] != 'D' {
return "", errors.Errorf("%v", word[0])
}
var digits int = len(word) - 1
for i, c := range word[1:] {
if c >= '0' && c <= '9' {
continue
}
digits = i
break
}
return word[:1+digits], nil
}
type circlePrimitive struct {
Exposure bool
Diameter float64
CenterX float64
CenterY float64
}
type vectorLinePrimitive struct {
Exposure bool
Width float64
StartX float64
StartY float64
EndX float64
EndY float64
Rotation float64
}
type outlinePrimitive struct {
Exposure bool
NumVertices int
Points [][2]float64
Rotation float64
}
type lowerLeftLinePrimitive struct {
Exposure bool
Width float64
Height float64
X float64
Y float64
Rotation float64
}
type template struct {
Line int
Name string
Primitives []interface{}
}
type LinePrimitiveNotClosedError struct {
Line int
First [2]float64
Last [2]float64
FirstStr [2]string
LastStr [2]string
}
func (err LinePrimitiveNotClosedError) Error() string {
return fmt.Sprintf("line primitive not closed %d %#v %#v", err.Line, err.First, err.Last)
}
func parsePrimitive(lineIdx int, word string) (interface{}, error) {
splitted := strings.Split(word, primitiveDelimiter)
if len(splitted) == 0 {
return nil, errors.Errorf("no splitted")
}
curLine := lineIdx
if strings.Contains(splitted[0], "\n") {
curLine++
}
code, err := strconv.Atoi(strings.TrimSpace(splitted[0]))
if err != nil {
return nil, errors.Wrap(err, "")
}
switch code {
case primitiveCodeCircle:
if len(splitted) != 5 {
return nil, errors.Errorf("%+v", splitted)
}
circle := circlePrimitive{}
exposure, err := strconv.Atoi(strings.TrimSpace(splitted[1]))
if err != nil {
return nil, errors.Wrap(err, "")
}
if exposure == 1 {
circle.Exposure = true
}
circle.Diameter, err = strconv.ParseFloat(strings.TrimSpace(splitted[2]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
circle.CenterX, err = strconv.ParseFloat(strings.TrimSpace(splitted[3]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
circle.CenterY, err = strconv.ParseFloat(strings.TrimSpace(splitted[4]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
return circle, nil
case primitiveCodeVectorLine:
if len(splitted) != 8 {
return nil, errors.Errorf("%+v", splitted)
}
line := vectorLinePrimitive{}
exposure, err := strconv.Atoi(strings.TrimSpace(splitted[1]))
if err != nil {
return nil, errors.Wrap(err, "")
}
if exposure == 1 {
line.Exposure = true
}
line.Width, err = strconv.ParseFloat(strings.TrimSpace(splitted[2]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
line.StartX, err = strconv.ParseFloat(strings.TrimSpace(splitted[3]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
line.StartY, err = strconv.ParseFloat(strings.TrimSpace(splitted[4]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
line.EndX, err = strconv.ParseFloat(strings.TrimSpace(splitted[5]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
line.EndY, err = strconv.ParseFloat(strings.TrimSpace(splitted[6]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
line.Rotation, err = strconv.ParseFloat(strings.TrimSpace(splitted[7]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
return line, nil
case primitiveCodeOutline:
line := outlinePrimitive{}
if len(splitted) < 3 {
return nil, errors.Errorf("%+v", splitted)
}
if strings.Contains(splitted[1], "\n") {
curLine++
}
exposure, err := strconv.Atoi(strings.TrimSpace(splitted[1]))
if err != nil {
return nil, errors.Wrap(err, "")
}
if exposure == 1 {
line.Exposure = true
}
if strings.Contains(splitted[2], "\n") {
curLine++
}
line.NumVertices, err = strconv.Atoi(strings.TrimSpace(splitted[2]))
if err != nil {
return nil, errors.Wrap(err, "")
}
if len(splitted) != 6+2*line.NumVertices {
return nil, errors.Errorf("%d", len(splitted))
}
points := make([][2]string, 0)
for i := 0; i < line.NumVertices+1; i++ {
if strings.Contains(splitted[2*i+3], "\n") {
curLine++
}
x, err := strconv.ParseFloat(strings.TrimSpace(splitted[2*i+3]), 64)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("%d", i))
}
if strings.Contains(splitted[2*i+4], "\n") {
curLine++
}
y, err := strconv.ParseFloat(strings.TrimSpace(splitted[2*i+4]), 64)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("%d", i))
}
line.Points = append(line.Points, [2]float64{x, y})
points = append(points, [2]string{strings.TrimSpace(splitted[2*i+3]), strings.TrimSpace(splitted[2*i+4])})
}
// The last point must be the same as the starting point.
if line.Points[0] != line.Points[len(line.Points)-1] {
return nil, LinePrimitiveNotClosedError{Line: curLine, First: line.Points[0], Last: line.Points[len(line.Points)-1], FirstStr: points[0], LastStr: points[len(points)-1]}
}
line.Points = line.Points[:len(line.Points)-1]
line.Rotation, err = strconv.ParseFloat(strings.TrimSpace(splitted[len(splitted)-1]), 64)
if err != nil {
return nil, errors.Errorf("%+v", splitted)
}
return line, nil
case primitiveCodeLowerLeftLine:
if len(splitted) != 7 {
return nil, errors.Errorf("%+v", splitted)
}
line := lowerLeftLinePrimitive{}
exposure, err := strconv.Atoi(strings.TrimSpace(splitted[1]))
if err != nil {
return nil, errors.Wrap(err, "")
}
if exposure == 1 {
line.Exposure = true
}
line.Width, err = strconv.ParseFloat(strings.TrimSpace(splitted[2]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
line.Height, err = strconv.ParseFloat(strings.TrimSpace(splitted[3]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
line.X, err = strconv.ParseFloat(strings.TrimSpace(splitted[4]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
line.Y, err = strconv.ParseFloat(strings.TrimSpace(splitted[5]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
line.Rotation, err = strconv.ParseFloat(strings.TrimSpace(splitted[6]), 64)
if err != nil {
return nil, errors.Wrap(err, "")
}
return line, nil
default:
return nil, errors.Errorf("%+v", splitted)
}
}
type aperture struct {
Line int
ID string
Template template
Params []float64
}
// A Segment is a stroked line.
type Segment struct {
Interpolation Interpolation
X int
Y int
CenterX int
CenterY int
}
// A Contour is a closed sequence of connected linear or circular segments.
type Contour struct {
Line int
X int
Y int
Segments []Segment
Polarity bool
}
type regionParser struct {
cp *commandProcessor
contour Contour
gotCommand bool
}
func newRegionParser(cp *commandProcessor, lineIdx int) *regionParser {
p := ®ionParser{}
p.cp = cp
p.contour = Contour{Line: lineIdx, X: cp.x, Y: cp.y, Polarity: cp.polarity}
return p
}
func (p *regionParser) process(lineIdx int, word string) error {
switch {
case strings.HasPrefix(word, commandG01):
p.cp.interpolation = InterpolationLinear
return p.process(lineIdx, word[len(commandG01):])
case strings.HasPrefix(word, commandG02):
p.cp.interpolation = InterpolationClockwise
return p.process(lineIdx, word[len(commandG02):])
case strings.HasPrefix(word, commandG03):
p.cp.interpolation = InterpolationCCW
return p.process(lineIdx, word[len(commandG03):])
case strings.HasSuffix(word, commandD01):
return p.processD01(lineIdx, word[:len(word)-len(commandD01)])
case strings.HasSuffix(word, commandD02):
return p.processD02(lineIdx, word[:len(word)-len(commandD02)])
case word == commandG37:
return p.cp.pc.Contour(p.contour)
case strings.HasPrefix(word, "X"):
return p.processModalD01(lineIdx, word)
default:
return errors.Errorf("unknown command")
}
}
func (p *regionParser) processModalD01(lineIdx int, word string) error {
if !p.cp.modalD01 {
return errors.Errorf("not in modal D01 mode")
}
return p.processD01(lineIdx, word)
}
func (p *regionParser) processD01(lineIdx int, word string) error {
coords, err := parseCoord(word)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("\"%s\"", word))
}
x, y := p.cp.findXY(coords)
s := Segment{Interpolation: p.cp.interpolation, X: x, Y: y}
switch s.Interpolation {
case InterpolationClockwise:
fallthrough
case InterpolationCCW:
i, j, err := p.cp.findIJ(coords)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("%+v", coords))
}
s.CenterX, s.CenterY = p.cp.x+i, p.cp.y+j
}
p.contour.Segments = append(p.contour.Segments, s)
p.cp.setXY(x, y)
p.cp.modalD01 = true
return nil
}
func (p *regionParser) processD02(lineIdx int, word string) error {
if p.gotCommand {
if err := p.cp.pc.Contour(p.contour); err != nil {
return errors.Wrap(err, "")
}
}
p.gotCommand = true
coords, err := parseCoord(word)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("\"%s\"", word))
}
x, y := p.cp.findXY(coords)
p.cp.setXY(x, y)
p.contour = Contour{Line: lineIdx, X: x, Y: y, Polarity: p.cp.polarity}
p.cp.modalD01 = false
return nil
}
// An Interpolation is a Gerber interpolation method.
type Interpolation int
// A LineCap is the shape at the endpoints of a line.
type LineCap string
const (
// Linear interpolation.
InterpolationLinear Interpolation = iota
// Clockwise arc interpolation
InterpolationClockwise
// Counter clockwise arc interpolation.
InterpolationCCW
// LineCapButt strokes do not extend beyond a line's two endpoints.
LineCapButt LineCap = "butt"
// LineCapRound strokes will be extended by a half circle with a diameter equal to the stroke width.
LineCapRound LineCap = "round"
primitiveCodeCircle = 1
primitiveCodeVectorLine = 20
primitiveCodeOutline = 4
primitiveCodeLowerLeftLine = 22
primitiveDelimiter = ","
commandFS = "FS"
commandMO = "MO"
commandG04 = "G04"
commandIP = "IP"
commandLN = "LN"
commandLP = "LP"
commandG74 = "G74"
commandG75 = "G75"
commandAD = "AD"
commandAM = "AM"
commandG36 = "G36"
commandG37 = "G37"
commandG54 = "G54"
commandG01 = "G01"
commandG02 = "G02"
commandG03 = "G03"
commandD01 = "D01"
commandD02 = "D02"
commandD03 = "D03"
commandSR = "SR"
commandM02 = "M02"
templateNameCircle = "C"
templateNameRectangle = "R"
templateNameObround = "O"
)
type commandProcessor struct {
pc Processor
templates map[string]template
apertures map[string]aperture
rp *regionParser
decimal float64
interpolation Interpolation
x int
y int
ap aperture
polarity bool
minX int
maxX int
minY int
maxY int
modalD01 bool
}
func newCommandProcessor(pc Processor) *commandProcessor {
p := &commandProcessor{}
p.pc = pc
p.templates = make(map[string]template)
p.apertures = make(map[string]aperture)
// Gerber RS-274X Format User guide.
// Part Number 414 100 014 Rev D March, 2001.
// Quote:
// When a new layer is generated, interpolation will be reset to linear (G01).
p.interpolation = InterpolationLinear
// Default polarity is dark.
p.polarity = true
p.minX = math.MaxInt
p.maxX = -math.MaxInt
p.minY = math.MaxInt
p.maxY = -math.MaxInt
return p
}
func (p *commandProcessor) processWord(lineIdx int, word string) error {
switch {
case p.rp != nil:
if err := p.rp.process(lineIdx, word); err != nil {
return errors.Wrap(err, fmt.Sprintf("%+v", p.rp))
}
if word == commandG37 {
p.rp = nil
}
return nil
}
switch {
case word == "":
return nil
case strings.HasPrefix(word, commandFS):
return p.processFS(lineIdx, word)
case strings.HasPrefix(word, commandMO):
return p.processMO(lineIdx, word)
case strings.HasPrefix(word, commandAD):
return p.parseAD(lineIdx, word[len(commandAD):])
case strings.HasPrefix(word, commandG04):
return nil
case strings.HasPrefix(word, commandLP):
return p.processLP(lineIdx, word)
case strings.HasPrefix(word, commandIP):
return nil
case strings.HasPrefix(word, commandLN):
return nil
case strings.HasPrefix(word, commandG74):
return nil
case strings.HasPrefix(word, commandG75):
return nil
case strings.HasPrefix(word, commandG54):
return p.processDnn(lineIdx, word[len(commandG54):])
case word == commandG36:
p.rp = newRegionParser(p, lineIdx)
return nil
case strings.HasPrefix(word, commandG01):
p.interpolation = InterpolationLinear
return p.processWord(lineIdx, word[len(commandG01):])
case strings.HasPrefix(word, commandG02):
p.interpolation = InterpolationClockwise
return p.processWord(lineIdx, word[len(commandG02):])
case strings.HasPrefix(word, commandG03):
p.interpolation = InterpolationCCW
return p.processWord(lineIdx, word[len(commandG03):])
case strings.HasSuffix(word, commandD01):
return p.processD01(lineIdx, word[:len(word)-len(commandD01)])
case strings.HasSuffix(word, commandD02):
return p.processD02(lineIdx, word[:len(word)-len(commandD02)])
case strings.HasSuffix(word, commandD03):
return p.processD03(lineIdx, word[:len(word)-len(commandD03)])
case strings.HasPrefix(word, "D"):
return p.processDnn(lineIdx, word)
case strings.HasPrefix(word, commandSR):
return p.processSR(lineIdx, word)
case strings.HasPrefix(word, "X"):
return p.processModalD01(lineIdx, word)
case word == commandM02:
p.pc.SetViewbox(p.minX, p.maxX, p.minY, p.maxY)
return nil
default:
return errors.Errorf("unknown command")
}
}
func (p *commandProcessor) setXY(x, y int) {
p.x = x
if x < p.minX {
p.minX = x
}
if x > p.maxX {
p.maxX = x
}
p.y = y
if y < p.minY {
p.minY = y
}
if y > p.maxY {
p.maxY = y
}
}
func (p *commandProcessor) processModalD01(lineIdx int, word string) error {
if !p.modalD01 {
return errors.Errorf("not in modal D01 mode")
}
return p.processD01(lineIdx, word)
}
func (p *commandProcessor) processD01(lineIdx int, word string) error {
coords, err := parseCoord(word)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("\"%s\"", word))
}
x, y := p.findXY(coords)
var diameter int
switch p.ap.Template.Name {
case templateNameCircle:
diameter = p.u(p.ap.Params[0])
case templateNameRectangle:
if p.ap.Params[0] != p.ap.Params[1] {
return errors.Errorf("%+v", p.ap)
}
diameter = p.u(p.ap.Params[0])
default:
return errors.Errorf("%+v", p.ap)
}
switch p.interpolation {
case InterpolationLinear:
p.pc.Line(lineIdx, p.x, p.y, x, y, diameter, LineCapRound)
case InterpolationClockwise:
fallthrough
case InterpolationCCW:
i, j, err := p.findIJ(coords)
if err != nil {
return errors.Errorf("%+v", coords)
}
xc, yc := p.x+i, p.y+j
if err := p.pc.Arc(lineIdx, p.x, p.y, x, y, xc, yc, p.interpolation, diameter); err != nil {
return errors.Wrap(err, "")
}
default:
return errors.Errorf("%d", p.interpolation)
}
p.setXY(x, y)
p.modalD01 = true
return nil
}
func (p *commandProcessor) processD02(lineIdx int, word string) error {
coords, err := parseCoord(word)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("\"%s\"", word))
}
x, y := p.findXY(coords)
p.setXY(x, y)
p.modalD01 = false
return nil
}
func (p *commandProcessor) processD03(lineIdx int, word string) error {
coords, err := parseCoord(word)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("\"%s\"", word))
}
x, y := p.findXY(coords)
p.setXY(x, y)
if err := p.flash(lineIdx); err != nil {
return errors.Wrap(err, "")
}
p.modalD01 = false
return nil
}
func (p *commandProcessor) flash(lineIdx int) error {
params := p.ap.Params
switch p.ap.Template.Name {
case templateNameCircle:
p.pc.Circle(lineIdx, p.x, p.y, p.u(params[0]), p.polarity)
case templateNameRectangle:
p.pc.Rectangle(lineIdx, p.x, p.y, p.u(params[0]), p.u(params[1]), p.polarity)
case templateNameObround:
p.pc.Obround(lineIdx, p.x, p.y, p.u(params[0]), p.u(params[1]), p.polarity)
default:
return p.flashUserDefinedTmpl(lineIdx)
}
return nil
}
func (p *commandProcessor) flashUserDefinedTmpl(lineIdx int) error {
if !p.polarity {
return errors.Errorf("%v", p.polarity)
}
if len(p.ap.Params) != 0 {
return errors.Errorf("%+v", p.ap)
}
for i, primitive := range p.ap.Template.Primitives {
switch pm := primitive.(type) {
case circlePrimitive:
if !pm.Exposure {
return errors.Errorf("%d %+v", i, pm)
}
p.pc.Circle(lineIdx, p.x+p.u(pm.CenterX), p.y+p.u(pm.CenterY), p.u(pm.Diameter), p.polarity)
case vectorLinePrimitive:
if !pm.Exposure {
return errors.Errorf("%d %+v", i, pm)
}
if pm.Rotation != 0 {
return errors.Errorf("%d %+v", i, pm)
}
p.pc.Line(lineIdx, p.x+p.u(pm.StartX), p.y+p.u(pm.StartY), p.x+p.u(pm.EndX), p.y+p.u(pm.EndY), p.u(pm.Width), LineCapButt)
case outlinePrimitive:
if !pm.Exposure {
return errors.Errorf("%d %+v", i, pm)
}
if pm.Rotation != 0 {
return errors.Errorf("%d %+v", i, pm)
}
contour, err := p.contourFromOutline(lineIdx, pm)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("%d %+v", i, pm))
}
if err := p.pc.Contour(contour); err != nil {
return errors.Wrap(err, fmt.Sprintf("%d %+v", i, pm))
}
case lowerLeftLinePrimitive:
if !pm.Exposure {
return errors.Errorf("%d %+v", i, pm)
}
if pm.Rotation != 0 {
return errors.Errorf("%d %+v", i, pm)
}
p.pc.Rectangle(lineIdx, p.x+p.u(pm.X+pm.Width/2), p.y+p.u(pm.Y+pm.Height/2), p.u(pm.Width), p.u(pm.Height), p.polarity)
default:
return errors.Errorf("%d %+v", i, p)
}
}
return nil
}
func (p *commandProcessor) contourFromOutline(lineIdx int, outline outlinePrimitive) (Contour, error) {
contour := Contour{Line: lineIdx, Polarity: p.polarity}
if len(outline.Points) < 3 {
return Contour{}, errors.Errorf("%+v", outline.Points)
}
contour.X = p.x + p.u(outline.Points[0][0])
contour.Y = p.y + p.u(outline.Points[0][1])
for _, pt := range outline.Points[1:] {
s := Segment{Interpolation: InterpolationLinear, X: p.x + p.u(pt[0]), Y: p.y + p.u(pt[1])}
contour.Segments = append(contour.Segments, s)
}
return contour, nil
}
type coord struct {
S byte
I int
}
func parseCoord(word string) ([]coord, error) {
if word == "" {
return nil, nil
}
coords := make([]coord, 0)
cur := coord{S: word[0]}
var digits []byte
var err error
for i, c := range []byte(word[1:]) {
switch {
case c == '+' || c == '-' || (c >= '0' && c <= '9'):
digits = append(digits, c)
default:
cur.I, err = strconv.Atoi(string(digits))
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("%d \"%s\"", i, digits))
}
coords = append(coords, cur)
cur = coord{}
cur.S = c
digits = digits[:0]
}
}
cur.I, err = strconv.Atoi(string(digits))
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("invalid digits \"%s\"", digits))
}
coords = append(coords, cur)
return coords, nil
}
func (p *commandProcessor) findXY(coords []coord) (int, int) {
x := p.x
for _, c := range coords {
if c.S == 'X' {
x = c.I
break
}
}
y := p.y
for _, c := range coords {
if c.S == 'Y' {
y = c.I
break
}
}
return x, y
}
func (p *commandProcessor) findIJ(coords []coord) (int, int, error) {
var i int
var got bool
for _, c := range coords {
if c.S == 'I' {
i = c.I
got = true
break
}
}
if !got {
return -math.MaxInt, -math.MaxInt, errors.Errorf("no i")
}
got = false
var j int
for _, c := range coords {
if c.S == 'J' {
j = c.I
got = true
break
}
}
if !got {
return -math.MaxInt, -math.MaxInt, errors.Errorf("no j")
}
return i, j, nil
}
func (p *commandProcessor) parseAD(lineIdx int, word string) error {
aperture := aperture{Line: lineIdx}
var err error
aperture.ID, err = parseApertureID(word)
if err != nil {
return errors.Wrap(err, "")
}
afterAID := word[len(aperture.ID):]
var tmplName string
commaIdx := strings.Index(afterAID, ",")
if commaIdx == -1 {
tmplName = afterAID
} else {
tmplName = afterAID[:commaIdx]
}
switch tmplName {
case templateNameCircle:
aperture.Template = template{Name: templateNameCircle}
case templateNameRectangle:
aperture.Template = template{Name: templateNameRectangle}
case templateNameObround:
aperture.Template = template{Name: templateNameObround}
default:
var ok bool
aperture.Template, ok = p.templates[tmplName]
if !ok {
tmpls := make([]string, 0, len(p.templates))
for k := range p.templates {
tmpls = append(tmpls, k)
}
return errors.Errorf("%s %+v", tmplName, tmpls)
}
}
if commaIdx != -1 {
if commaIdx+1 > len(afterAID) {
return errors.Errorf("%d %s", commaIdx, afterAID)
}
params := strings.Split(afterAID[commaIdx+1:], "X")
for i, pStr := range params {
p, err := strconv.ParseFloat(pStr, 64)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("%d", i))
}
aperture.Params = append(aperture.Params, p)
}
}
var expectedParams int = len(aperture.Params)
switch tmplName {
case templateNameCircle:
expectedParams = 1
case templateNameRectangle:
expectedParams = 2
case templateNameObround:
expectedParams = 2
}
if expectedParams != len(aperture.Params) {
return errors.Errorf("%d %+v", expectedParams, aperture.Params)
}
if prev, ok := p.apertures[aperture.ID]; ok {
return errors.Errorf("%+v", prev)
}
p.apertures[aperture.ID] = aperture
return nil
}
func (p *commandProcessor) processFS(lineIdx int, word string) error {
if len(word) < 7 {
return errors.Errorf("%d", len(word))
}
decimal, err := strconv.Atoi(word[6:7])
if err != nil {
return errors.Wrap(err, "")
}
p.decimal = math.Pow(10, float64(decimal))
p.pc.SetDecimal(p.decimal)
return nil
}
func (p *commandProcessor) u(f float64) int {
return int(math.Round(f * p.decimal))
}
func (p *commandProcessor) processMO(lineIdx int, word string) error {
if len(word) != 4 {
return errors.Errorf("%d", len(word))
}
unit := word[2:]
switch unit {
case "MM":
return nil
case "IN":
return nil
default:
return errors.Errorf("%s", unit)
}
}
func (p *commandProcessor) processSR(lineIdx int, word string) error {
if word != "SRX1Y1I0J0" {
return errors.Errorf("unsupported SR")
}
return nil
}
func (p *commandProcessor) processLP(lineIdx int, word string) error {
if len(word) != 3 {
return errors.Errorf("%d", len(word))
}
switch word[2] {
case 'D':
p.polarity = true
case 'C':
p.polarity = false
default:
return errors.Errorf("%s", word)
}
return nil
}
func (p *commandProcessor) processDnn(lineIdx int, word string) error {
var ok bool
p.ap, ok = p.apertures[word]
if !ok {
aps := make([]string, 0, len(p.apertures))
for k := range p.apertures {
aps = append(aps, k)
}
return errors.Errorf("%+v", aps)
}
p.modalD01 = false
return nil
}
func (p *commandProcessor) processExtended(lineIdx int, words []string) error {
if len(words) == 0 {
return errors.Errorf("no words")
}
switch {
case strings.HasPrefix(words[0], commandAM):
tmpl := template{Line: lineIdx, Name: words[0][len(commandAM):]}
for _, w := range words[1:] {
primitive, err := parsePrimitive(lineIdx, w)
if err != nil {
return errors.Wrap(err, "")
}
tmpl.Primitives = append(tmpl.Primitives, primitive)
}
p.templates[tmpl.Name] = tmpl
default:
return errors.Errorf("unknown command")
}
return nil
}
// A Parser is a Gerber format parser.
// For each graphical operation parsed from an input stream,
// Parser calls the corresponding method of its Processor.
type Parser struct {
cmdStart int
cmdLines []string
cmdProcessor *commandProcessor
}