Welcome to mirror list, hosted at ThFree Co, Russian Federation.

GerberDocument.cs « Gerber « UVtools.Core - github.com/sn4k3/UVtools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: eca46fbb74e82585ea000891b27fc72f38e54827 (plain)
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
/*
 *                     GNU AFFERO GENERAL PUBLIC LICENSE
 *                       Version 3, 19 November 2007
 *  Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 *  Everyone is permitted to copy and distribute verbatim copies
 *  of this license document, but changing it is not allowed.
 */

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using UVtools.Core.Extensions;
using UVtools.Core.Gerber.Apertures;

namespace UVtools.Core.Gerber;

/// <summary>
/// https://www.ucamco.com/files/downloads/file_en/456/gerber-layer-format-specification-revision-2022-02_en.pdf?ac97011bf6bce9aaf0b1aac43d84b05f
/// </summary>
public class GerberDocument
{
    #region Properties

    public GerberZerosSuppressionType ZerosSuppressionType { get; set; } = GerberZerosSuppressionType.NoSuppression;
    public GerberPositionType PositionType { get; set; } = GerberPositionType.Absolute;
    public GerberUnitType UnitType { get; set; } = GerberUnitType.Millimeter;
    public GerberPolarityType Polarity { get; set; } = GerberPolarityType.Dark;
    public GerberMoveType MoveType { get; set; } = GerberMoveType.Linear;
    public GerberMidpointRounding SizeMidpointRounding { get; set; } = GerberMidpointRounding.AwayFromZero;

    public byte CoordinateXIntegers { get; set; } = 3;
    public byte CoordinateXFractionalDigits { get; set; } = 6;

    public byte CoordinateXLength => (byte)(CoordinateXIntegers + CoordinateXFractionalDigits);

    public byte CoordinateYIntegers { get; set; } = 3;
    public byte CoordinateYFractionalDigits { get; set; } = 6;

    public byte CoordinateYLength => (byte)(CoordinateYIntegers + CoordinateYFractionalDigits);

    public Dictionary<int, Aperture> Apertures { get; } = new();
    public Dictionary<string, Macro> Macros { get; } = new();

    public SizeF XYppmm { get; init; }

    public MCvScalar PolarityColor => Polarity == GerberPolarityType.Dark ? EmguExtensions.WhiteColor : EmguExtensions.BlackColor;

    #endregion


    public GerberDocument()
    {
    }

    public GerberDocument(string filePath)
    {
    }

    public static GerberDocument ParseAndDraw(string filePath, Mat mat, SizeF xyPpmm, GerberMidpointRounding sizeMidpointRounding = GerberMidpointRounding.AwayFromZero, bool enableAntialiasing = false)
    {
        using var file = new StreamReader(filePath);
        var document = new GerberDocument
        {
            SizeMidpointRounding = sizeMidpointRounding,
            XYppmm = xyPpmm
        };

        int FSlength = "%FSLAX46Y46*%".Length;
        int MOlength = "%MOMM*%".Length;
        int LPlength = "%LPD*%".Length;

        double currentX = 0;
        double currentY = 0;
        Aperture? currentAperture = null;
        Macro? currentMacro = null;
        var regionPoints = new List<Point>();
        bool insideRegion = false;
        string? line;
        while ((line = file.ReadLine()) is not null)
        {
            line = line.Trim();
            if(line == string.Empty) continue;
            if (line.StartsWith("M02")) break;

            var accumulatedLine = line;
            while (!accumulatedLine.Contains('*') && (line = file.ReadLine()) is not null)
            {
                line = line.Trim();
                if (line == string.Empty) continue;
                accumulatedLine += line;
            }

            line = accumulatedLine;

            if(currentMacro is not null)
            {
                currentMacro.ParsePrimitive(line);
                if (line[^1] == '%') currentMacro = null;
                continue;
            }

            if (line.StartsWith("%MO") && line.Length >= MOlength)
            {
                if(line[3] == 'M' && line[4] == 'M') document.UnitType = GerberUnitType.Millimeter;
                else if(line[3] == 'I' && line[4] == 'N') document.UnitType = GerberUnitType.Inch;
                continue;
            }

            if (line.StartsWith("G70"))
            {
                document.UnitType = GerberUnitType.Inch;
                continue;
            }


            if (line.StartsWith("G71"))
            {
                document.UnitType = GerberUnitType.Millimeter;
                continue;
            }

            if (line.StartsWith("G90"))
            {
                document.PositionType = GerberPositionType.Absolute;
                continue;
            }


            if (line.StartsWith("G91"))
            {
                document.PositionType = GerberPositionType.Relative;
                continue;
            }

            if (line.StartsWith("%FS") && line.Length >= FSlength) 
            {
                // %FSLAX34Y34*%
                // 0123456789
                document.ZerosSuppressionType = line[3] switch
                {
                    'L' => GerberZerosSuppressionType.Leading,
                    'T' => GerberZerosSuppressionType.Trail,
                    _ => document.ZerosSuppressionType
                };
                document.PositionType = line[4] switch
                {
                    'A' => GerberPositionType.Absolute,
                    'I' => GerberPositionType.Relative,
                    _ => document.PositionType
                };
                if (document.PositionType == GerberPositionType.Relative) throw new NotImplementedException("Relative positions are not implemented yet.\nPlease use Absolute position for now.");
                if (line[5] != 'X') continue;
                if (byte.TryParse(line[6].ToString(), out var x1)) document.CoordinateXIntegers = x1;
                if (byte.TryParse(line[7].ToString(), out var x2)) document.CoordinateXFractionalDigits = x2;
                if (line[8] != 'Y') continue;
                if (byte.TryParse(line[9].ToString(), out var y1)) document.CoordinateYIntegers = y1;
                if (byte.TryParse(line[10].ToString(), out var y2)) document.CoordinateYFractionalDigits = y2;
                continue;
            }

            if (line.StartsWith("%LP") && line.Length >= LPlength)
            {
                document.Polarity = line[3] switch
                {
                    'D' => GerberPolarityType.Dark,
                    'C' => GerberPolarityType.Clear,
                    _ => document.Polarity
                };

                continue;
            }

            if (line.StartsWith("G01"))
            {
                document.MoveType = GerberMoveType.Linear;
                continue;
            }

            if (line.StartsWith("G02"))
            {
                document.MoveType = GerberMoveType.Arc;
                continue;
            }

            if (line.StartsWith("G03"))
            {
                document.MoveType = GerberMoveType.ArcCounterClockwise;
                continue;
            }

            if (line.StartsWith("G36"))
            {
                insideRegion = true;
                regionPoints.Clear();
                continue;
            }

            if (line.StartsWith("G37"))
            {
                insideRegion = false;
                if (regionPoints.Count > 0)
                {
                    using var vec = new VectorOfPoint(regionPoints.ToArray());
                    CvInvoke.FillPoly(mat, vec, document.PolarityColor, enableAntialiasing ? LineType.AntiAlias : LineType.EightConnected);
                }
                //CvInvoke.Imshow("G37", mat);
                //CvInvoke.WaitKey();
                regionPoints.Clear();
                continue;
            }

            if (line.StartsWith("%AM"))
            {
                currentMacro = Macro.Parse(document, line);
                if (currentMacro is null) continue;
                document.Macros.Add(currentMacro.Name, currentMacro);
                //document.Apertures.Add(aperture.Index, aperture);
                continue;
            }

            if (line.StartsWith("%ADD"))
            {
                var aperture = Aperture.Parse(line, document);
                if (aperture is null) continue;
                currentAperture = aperture;
                document.Apertures.Add(aperture.Index, aperture);
                continue;
            }

            // Aperture selector
            if (line[0] == 'D')
            {
                var matchD = Regex.Match(line, @"D(\d+)");
                if (!matchD.Success || matchD.Groups.Count < 2) continue;

                if (!int.TryParse(matchD.Groups[1].Value, out var d)) continue;

                if (d >= 10)
                {
                    document.Apertures.TryGetValue(d, out currentAperture);
                    continue;
                }
            }


            if (line[0] == 'X' || line[0] == 'Y' || line[0] == 'D')
            {
                var matchX = Regex.Match(line, @"X-?(\d+)?");
                var matchY = Regex.Match(line, @"Y-?(\d+)?");
                var matchD = Regex.Match(line, @"D(\d+)");

                double nowX = 0;
                double nowY = 0;

                if (!matchD.Success || matchD.Groups.Count < 2) continue;
                if (!int.TryParse(matchD.Groups[1].Value, out var d)) continue;

                if (matchX.Success)
                {
                    if (matchX.Groups.Count >= 2)
                    {
                        var valueStr = document.ZerosSuppressionType switch
                        {
                            GerberZerosSuppressionType.Trail => matchX.Groups[1].Value.PadRight(document.CoordinateXLength, '0'),
                            _ => matchX.Groups[1].Value.PadLeft(document.CoordinateXLength, '0'),
                        };

                        var integers = valueStr[..document.CoordinateXIntegers];
                        var fraction = valueStr[document.CoordinateXIntegers..];
                        double.TryParse($"{integers}.{fraction}", out nowX);
                        nowX = document.GetMillimeters(nowX);
                    }
                }
                else
                {
                    nowX = currentX;
                }

                if (matchY.Success)
                {
                    if (matchY.Groups.Count >= 2)
                    {
                        var valueStr = document.ZerosSuppressionType switch
                        {
                            GerberZerosSuppressionType.Trail => matchY.Groups[1].Value.PadRight(document.CoordinateYLength, '0'),
                            _ => matchY.Groups[1].Value.PadLeft(document.CoordinateYLength, '0'),
                        };

                        var integers = valueStr[..document.CoordinateYIntegers];
                        var fraction = valueStr[document.CoordinateYIntegers..];
                        double.TryParse($"{integers}.{fraction}", out nowY);
                        nowY = document.GetMillimeters(nowY);

                    }
                }
                else
                {
                    nowY = currentY;
                }

                if (insideRegion)
                {
                    if (d == 2)
                    {
                        if (regionPoints.Count > 0)
                        {
                            using var vec = new VectorOfPoint(regionPoints.ToArray());
                            CvInvoke.FillPoly(mat, vec, document.PolarityColor, enableAntialiasing ? LineType.AntiAlias : LineType.EightConnected);
                        }
                        regionPoints.Clear();
                    }

                    var pt = document.PositionMmToPx(nowX, nowY);
                    if (regionPoints.Count == 0 || (regionPoints.Count > 0 && regionPoints[^1] != pt)) regionPoints.Add(pt);
                }
                else if(currentAperture is not null)
                {
                    if (d == 1)
                    {
                        if (currentAperture is CircleAperture circleAperture)
                        {
                            if (document.MoveType is GerberMoveType.Arc or GerberMoveType.ArcCounterClockwise)
                            {
                                double xOffset = 0;
                                double yOffset = 0;
                                var matchI = Regex.Match(line, @"I(-?\d+)");
                                var matchJ = Regex.Match(line, @"J(-?\d+)");
                                if(!matchI.Success || !matchJ.Success || matchI.Groups.Count < 2 || matchJ.Groups.Count < 2) continue;


                                var valueStr = document.ZerosSuppressionType switch
                                {
                                    GerberZerosSuppressionType.Trail => matchI.Groups[1].Value.PadRight(document.CoordinateXLength, '0'),
                                    _ => matchI.Groups[1].Value.PadLeft(document.CoordinateXLength, '0'),
                                };


                                var integers = valueStr[..document.CoordinateXIntegers];
                                var fraction = valueStr[document.CoordinateXIntegers..];
                                double.TryParse($"{integers}.{fraction}", out xOffset);
                                xOffset = document.GetMillimeters(xOffset);


                                valueStr = document.ZerosSuppressionType switch
                                {
                                    GerberZerosSuppressionType.Trail => matchJ.Groups[1].Value.PadRight(document.CoordinateYLength, '0'),
                                    _ => matchJ.Groups[1].Value.PadLeft(document.CoordinateYLength, '0'),
                                };


                                integers = valueStr[..document.CoordinateYIntegers];
                                fraction = valueStr[document.CoordinateYIntegers..];
                                double.TryParse($"{integers}.{fraction}", out yOffset);
                                yOffset = document.GetMillimeters(yOffset);


                                if (currentX == nowX && currentY == nowY) // Closed circle
                                {
                                    CvInvoke.Ellipse(mat,
                                        document.PositionMmToPx(nowX + xOffset, nowY + yOffset),
                                        document.SizeMmToPx(Math.Abs(xOffset), Math.Abs(xOffset)),
                                        0, 0, 360.0, document.PolarityColor,
                                        document.SizeMmToPx(circleAperture.Diameter),
                                        enableAntialiasing ? LineType.AntiAlias : LineType.EightConnected
                                    );
                                }
                                else
                                {
                                    // TODO: Fix this
                                    throw new NotImplementedException("Partial arcs are not yet implemented (G03)\nTo be fixed in the future...");
                                    /*CvInvoke.Ellipse(mat, new Point((int)((nowX + xOffset) * xyPpmm.Width), (int)((currentY) * xyPpmm.Height)),
                                        new Size((int)(Math.Abs(xOffset) * xyPpmm.Width), (int)(Math.Abs(yOffset) * xyPpmm.Width)),
                                        0, Math.Abs(currentY - nowY), 360.0 / Math.Abs(currentX - nowX), document.PolarityColor,
                                        (int)(circleAperture.Diameter * xyPpmm.Max()),
                                        enableAntialiasing ? LineType.AntiAlias : LineType.EightConnected
                                    );*/
                                }
                                    
                            }
                            else
                            {
                                CvInvoke.Line(mat,
                                    document.PositionMmToPx(currentX, currentY),
                                    document.PositionMmToPx(nowX, nowY),
                                    document.PolarityColor,
                                    EmguExtensions.CorrectThickness(document.SizeMmToPx(circleAperture.Diameter)),
                                    enableAntialiasing ? LineType.AntiAlias : LineType.EightConnected);
                                /*mat.DrawLineAccurate(PositionMmToPx(currentX, currentY, xyPpmm),
                                    PositionMmToPx(nowX, nowY, xyPpmm),
                                    document.PolarityColor
                                    SizeMmToPx(circleAperture.Diameter, xyPpmm.Max()),
                                    enableAntialiasing ? LineType.AntiAlias : LineType.EightConnected);*/

                                /*CvInvoke.DrawContours(mat, new VectorOfVectorOfPoint(new[]
                                {
                                    new []
                                    {
                                        PositionMmToPx(currentX, currentY, xyPpmm),
                                        PositionMmToPx(nowX, nowY, xyPpmm),
                                    }
                                }), -1, document.PolarityColor, SizeMmToPx(circleAperture.Diameter, xyPpmm.Max()));*/
                                //CvInvoke.Imshow("Line", mat);
                                //CvInvoke.WaitKey();
                            }
                                
                        }
                    }
                    else if (d == 3)
                    {
                        currentAperture.DrawFlashD3(mat, new PointF((float) nowX, (float) nowY), 
                            document.PolarityColor, enableAntialiasing ? LineType.AntiAlias : LineType.EightConnected);
                        //CvInvoke.Imshow("G37", mat);
                        //CvInvoke.WaitKey();
                    }
                }

                currentX = nowX;
                currentY = nowY;
                continue;
            }
        }

        return document;
    }

    public float GetMillimeters(float size)
    {
        if (UnitType == GerberUnitType.Millimeter) return size;
        return size * (float)UnitExtensions.InchToMillimeter;
    }

    public double GetMillimeters(double size)
    {
        if (UnitType == GerberUnitType.Millimeter) return size;
        return size * UnitExtensions.InchToMillimeter;
    }

    public SizeF GetMillimeters(SizeF size)
    {
        if (UnitType == GerberUnitType.Millimeter) return size;
        return new SizeF(size.Width * (float)UnitExtensions.InchToMillimeter, size.Height * (float)UnitExtensions.InchToMillimeter);
    }

    public PointF GetMillimeters(PointF point)
    {
        if (UnitType == GerberUnitType.Millimeter) return point;
        return new PointF(point.X * (float)UnitExtensions.InchToMillimeter, point.Y * (float)UnitExtensions.InchToMillimeter);
    }

    public Point PositionMmToPx(PointF atMm)
        => new((int)Math.Round(atMm.X * XYppmm.Width, MidpointRounding.AwayFromZero), (int)Math.Round(atMm.Y * XYppmm.Height, MidpointRounding.AwayFromZero));

    public Point PositionMmToPx(double atXmm, double atYmm)
        => new((int)Math.Round(atXmm * XYppmm.Width, MidpointRounding.AwayFromZero), (int)Math.Round(atYmm * XYppmm.Height, MidpointRounding.AwayFromZero));

    public Point PositionMmToPx(float atXmm, float atYmm)
        => new((int)Math.Round(atXmm * XYppmm.Width, MidpointRounding.AwayFromZero), (int)Math.Round(atYmm * XYppmm.Height, MidpointRounding.AwayFromZero));

    public Size SizeMmToPx(SizeF sizeMm)
        => new((int)Math.Max(1, Math.Round(sizeMm.Width * XYppmm.Width, (MidpointRounding)SizeMidpointRounding)),
            (int)Math.Max(1, Math.Round(sizeMm.Height * XYppmm.Height, (MidpointRounding)SizeMidpointRounding)));

    public Size SizeMmToPx(double sizeXmm, double sizeYmm)
        => new((int)Math.Max(1, Math.Round(sizeXmm * XYppmm.Width, (MidpointRounding)SizeMidpointRounding)),
            (int)Math.Max(1, Math.Round(sizeYmm * XYppmm.Height, (MidpointRounding)SizeMidpointRounding)));

    public Size SizeMmToPx(float sizeXmm, float sizeYmm)
        => new((int)Math.Max(1, Math.Round(sizeXmm * XYppmm.Width, (MidpointRounding)SizeMidpointRounding)),
            (int)Math.Max(1, Math.Round(sizeYmm * XYppmm.Height, (MidpointRounding)SizeMidpointRounding)));

    public int SizeMmToPx(float sizeMm)
        => (int) Math.Max(1, Math.Round(sizeMm * XYppmm.Max(), (MidpointRounding)SizeMidpointRounding));

    public int SizeMmToPx(double sizeMm)
        => (int)Math.Max(1, Math.Round(sizeMm * XYppmm.Max(), (MidpointRounding)SizeMidpointRounding));

    public int SizeMmToPxOverride(float sizeMm, float ppmm)
        => (int)Math.Max(1, Math.Round(sizeMm * ppmm, (MidpointRounding)SizeMidpointRounding));

    public int SizeMmToPxOverride(double sizeMm, float ppmm)
        => (int)Math.Max(1, Math.Round(sizeMm * ppmm, (MidpointRounding)SizeMidpointRounding));
}


/* KIDCAD
        var document = File.ReadAllLines(@"D:\Tiago\Desktop\kisample\kisample.kicad_pcb");
        System.Drawing.PointF location = PointF.Empty;

        using var mat = EmguExtensions.InitMat(new System.Drawing.Size(2440, 1440));
        const byte pixelsPerMm = 20;

        var drillPoints = new List<KeyValuePair<Point, int>>();

        foreach (var line in document)
        {
            var parseLine = line.Trim();
            if (parseLine.StartsWith("(footprint "))
            {
                location = PointF.Empty;
                continue;
            }
            if (location.IsEmpty && parseLine.StartsWith("(at "))
            {
                parseLine = parseLine.Substring(4, parseLine.Length-5);
                var split = parseLine.Split(' ');
                location = new PointF(float.Parse(split[0]), float.Parse(split[1]));
                continue;
            }
            if (parseLine.StartsWith("(segment ") || parseLine.StartsWith("(gr_line "))
            {
                var layerMatch = Regex.Match(parseLine, @"\S.Cu");
                if (!layerMatch.Success || layerMatch.Groups.Count < 1) continue;

                var startMatch = Regex.Match(parseLine, @"\(start\s+(\S+)\s+(\S+)\)");
                if(!startMatch.Success || startMatch.Groups.Count < 3) continue;

                var endMatch = Regex.Match(parseLine, @"\(end\s+(\S+)\s+(\S+)\)");
                if (!endMatch.Success || endMatch.Groups.Count < 3) continue;

                var widthMatch = Regex.Match(parseLine, @"\(width\s+(\S+)\)");
                if (!widthMatch.Success || widthMatch.Groups.Count < 2) continue;

                var startXf = new PointF(float.Parse(startMatch.Groups[1].Value), float.Parse(startMatch.Groups[2].Value));
                var endXf = new PointF(float.Parse(endMatch.Groups[1].Value), float.Parse(endMatch.Groups[2].Value));
                var widthf = float.Parse(widthMatch.Groups[1].Value);

                var startX = new System.Drawing.Point((int)(startXf.X * pixelsPerMm), (int)(startXf.Y * pixelsPerMm));
                var endX = new System.Drawing.Point((int)(endXf.X * pixelsPerMm), (int)(endXf.Y * pixelsPerMm));
                var width = (int) (widthf * pixelsPerMm);

                CvInvoke.Line(mat, startX, endX, EmguExtensions.WhiteColor, width);

                continue;
            }

            if (parseLine.StartsWith("(via "))
            {
                var layerMatches = Regex.Matches(parseLine, @"\S.Cu");
                if (layerMatches.Count < 1) continue;
                
                var atMatch = Regex.Match(parseLine, @"\(at\s+(\S+)\s+(\S+)\)");
                if (!atMatch.Success || atMatch.Groups.Count < 3) continue;

                var drillMatch = Regex.Match(parseLine, @"\(drill\s+(\S+)\)");


                var atf = new PointF(float.Parse(atMatch.Groups[1].Value), float.Parse(atMatch.Groups[2].Value));
                //var sizef = new SizeF(float.Parse(sizeMatch.Groups[1].Value), float.Parse(sizeMatch.Groups[2].Value));

                var at = new System.Drawing.Point((int)(atf.X * pixelsPerMm), (int)(atf.Y * pixelsPerMm));
                if (!drillMatch.Success || drillMatch.Groups.Count < 2) continue;
                var drillf = float.Parse(drillMatch.Groups[1].Value);
                var drill = (int) (drillf * pixelsPerMm / 2);

                CvInvoke.Circle(mat, at, drill, EmguExtensions.WhiteColor, -1);


                continue;
            }

            if (parseLine.StartsWith("(gr_circle "))
            {
                var layerMatch = Regex.Match(parseLine, @"\S.Cu");
                if (!layerMatch.Success || layerMatch.Groups.Count < 1) continue;

                var atMatch = Regex.Match(parseLine, @"\(center\s+(\S+)\s+(\S+)\)");
                if (!atMatch.Success || atMatch.Groups.Count < 3) continue;

                var endMatch = Regex.Match(parseLine, @"\(end\s+(\S+)\s+(\S+)\)");
                if (!endMatch.Success || endMatch.Groups.Count < 3) continue;

                var widthMatch = Regex.Match(parseLine, @"\(width\s+(\S+)\)");
                if (!widthMatch.Success || widthMatch.Groups.Count < 2) continue;

                var atf = new PointF(float.Parse(atMatch.Groups[1].Value), float.Parse(atMatch.Groups[2].Value));
                var at = new System.Drawing.Point((int)(atf.X * pixelsPerMm), (int)(atf.Y * pixelsPerMm));
                var endf = new PointF(float.Parse(endMatch.Groups[1].Value), float.Parse(endMatch.Groups[2].Value));
                var radius = (int)(Math.Max(Math.Abs(atf.X - endf.X), Math.Abs(atf.Y - endf.Y)) * pixelsPerMm);
                var widthf = float.Parse(widthMatch.Groups[1].Value);
                var width = (int)(widthf * pixelsPerMm);

                CvInvoke.Circle(mat, at, radius, EmguExtensions.WhiteColor, width);
                if (parseLine.Contains("fill solid"))
                {
                    CvInvoke.Circle(mat, at, radius, EmguExtensions.WhiteColor, -1);
                }


                continue;
            }
            if (parseLine.StartsWith("(gr_rect "))
            {
                var layerMatch = Regex.Match(parseLine, @"\S.Cu");
                if (!layerMatch.Success || layerMatch.Groups.Count < 1) continue;

                var startMatch = Regex.Match(parseLine, @"\(start\s+(\S+)\s+(\S+)\)");
                if (!startMatch.Success || startMatch.Groups.Count < 3) continue;

                var endMatch = Regex.Match(parseLine, @"\(end\s+(\S+)\s+(\S+)\)");
                if (!endMatch.Success || endMatch.Groups.Count < 3) continue;

                var widthMatch = Regex.Match(parseLine, @"\(width\s+(\S+)\)");
                if (!widthMatch.Success || widthMatch.Groups.Count < 2) continue;

                var startf = new PointF(float.Parse(startMatch.Groups[1].Value), float.Parse(startMatch.Groups[2].Value));
                var endf = new PointF(float.Parse(endMatch.Groups[1].Value), float.Parse(endMatch.Groups[2].Value));
                var widthf = float.Parse(widthMatch.Groups[1].Value);

                var start = new System.Drawing.Point((int)(startf.X * pixelsPerMm), (int)(startf.Y * pixelsPerMm));
                var end = new System.Drawing.Point((int)(endf.X * pixelsPerMm), (int)(endf.Y * pixelsPerMm));
                var width = (int)(widthf * pixelsPerMm);

                CvInvoke.Rectangle(mat, new Rectangle(start, new System.Drawing.Size(end.X - start.X, end.Y - start.Y)), EmguExtensions.WhiteColor, width);
                if (parseLine.Contains("fill solid"))
                {
                    CvInvoke.Rectangle(mat, new Rectangle(start, new System.Drawing.Size(end.X - start.X, end.Y - start.Y)), EmguExtensions.WhiteColor, -1);
                }

                continue;
            }

            if (location.IsEmpty) continue;

            if (parseLine.StartsWith("(pad "))
            {
                var layerMatch = Regex.Match(parseLine, @"\S.Cu");
                if (!layerMatch.Success || layerMatch.Groups.Count < 1) continue;

                var atMatch = Regex.Match(parseLine, @"\(at\s+(\S+)\s+(\S+)\)");
                if (!atMatch.Success || atMatch.Groups.Count < 3) continue;
                
                var sizeMatch = Regex.Match(parseLine, @"\(size\s+(\S+)\s+(\S+)\)");
                if (!sizeMatch.Success || sizeMatch.Groups.Count < 3) continue;

                var drillMatch = Regex.Match(parseLine, @"\(drill\s+(\S+)\)");


                var atf = new PointF(float.Parse(atMatch.Groups[1].Value), float.Parse(atMatch.Groups[2].Value));
                var sizef = new SizeF(float.Parse(sizeMatch.Groups[1].Value), float.Parse(sizeMatch.Groups[2].Value));

                var at = new System.Drawing.Point((int)(location.X * pixelsPerMm + atf.X * pixelsPerMm), (int)(location.Y * pixelsPerMm + atf.Y * pixelsPerMm));

                if (parseLine.Contains(" rect ") || parseLine.Contains(" roundrect "))
                {
                    var size = new System.Drawing.Size((int)(sizef.Width * pixelsPerMm), (int)(sizef.Height * pixelsPerMm));
                    var rect = new Rectangle(at, size);
                    rect.Offset(-size.Width / 2, -size.Height / 2);
                    CvInvoke.Rectangle(mat, rect, EmguExtensions.WhiteColor, -1);
                }
                else if (parseLine.Contains(" oval ") || parseLine.Contains(" circle "))
                {
                    var size = new System.Drawing.Size((int)(sizef.Width / 2 * pixelsPerMm), (int)(sizef.Height / 2 * pixelsPerMm));
                    CvInvoke.Ellipse(mat, at, size, 0, 0, 360, EmguExtensions.WhiteColor, -1);
                }
                
                if (drillMatch.Success && drillMatch.Groups.Count >= 2)
                {
                    var drillf = float.Parse(drillMatch.Groups[1].Value);
                    var drill = (int)(drillf * pixelsPerMm / 2);

                    drillPoints.Add(new KeyValuePair<Point, int>(at, drill));
                }


                continue;
            }
        }

        foreach (var pair in drillPoints)
        {
            CvInvoke.Circle(mat, pair.Key, pair.Value, EmguExtensions.BlackColor, -1);
        }

        CvInvoke.Imshow("asd", mat);
        CvInvoke.WaitKey();
        return;
        */