void DoThread()
        {
            double DPI = 0;

            if (!double.TryParse(DPIbox.Text, out DPI))
            {
                DPI = 200;
            }


            string OutlineFile = OutlineFileBox.Text;

            ParsedGerber PLS = null;

            PLS = PolyLineSet.LoadGerberFile(OutlineFile);

            string SilkFile       = SilkFileTopBox.Text;
            string BitmapFile     = BitmapFileTopBox.Text;
            bool   Flipped        = FlipBox.Checked;
            bool   FlippedBottom  = FlipInputBottom.Checked;
            bool   Invert         = InvertBox.Checked;
            bool   InvertBottom   = InvertBitmapBottom.Checked;
            string CopperFile     = copperfilebox.Text;
            string soldermaskfile = soldermaskfilebox.Text;

            statustext = "processing top!";
            CreateStuff(DPI, PLS, OutlineFile, SilkFile, BitmapFile, Flipped, Invert, CopperFile, soldermaskfile);
            statustext = "processing bottom!";
            CreateStuff(DPI, PLS, OutlineFile, SilkFileBottomBox.Text, BitmapFileBottomBox.Text, FlippedBottom, InvertBottom, CopperFile, soldermaskfile);

            BGThread   = null;
            statustext = "done!";
        }
Esempio n. 2
0
        private void ProcessButton_Click(object sender, EventArgs e)
        {
            // Process

            double DPI = 0;

            if (!double.TryParse(DPIbox.Text, out DPI))
            {
                DPI = 200;
            }


            string OutlineFile = OutlineFileBox.Text;

            ParsedGerber PLS = null;

            PLS = PolyLineSet.LoadGerberFile(OutlineFile);

            string SilkFile       = SilkFileTopBox.Text;
            string BitmapFile     = BitmapFileTopBox.Text;
            bool   Flipped        = FlipBox.Checked;
            bool   Invert         = InvertBox.Checked;
            string CopperFile     = copperfilebox.Text;
            string soldermaskfile = soldermaskfilebox.Text;

            CreateStuff(DPI, PLS, OutlineFile, SilkFile, BitmapFile, Flipped, Invert, CopperFile, soldermaskfile);
            ///CreateStuff(DPI, PLS, OutlineFile, SilkFileBottomBox.Text, BitmapFileBottomBox.Text, FlipInputBottom.Checked, InvertBitmapBottom.Checked);
        }
Esempio n. 3
0
        static void ConvertFile(string from, string to, bool displayshapes, bool outlineshapes)
        {
            ParsedGerber PLS = PolyLineSet.LoadGerberFile(new StandardConsoleLog(), from, true, State: new GerberParserState()
            {
                PreCombinePolygons = true
            });



            DxfDocument dxf = new DxfDocument();

            // add your entities here


            if (outlineshapes)
            {
                foreach (var a in PLS.OutlineShapes)
                {
                    List <netDxf.Entities.PolylineVertex> Vertices = new List <netDxf.Entities.PolylineVertex>();
                    foreach (var v in a.Vertices)
                    {
                        Vertices.Add(new netDxf.Entities.PolylineVertex(v.X, v.Y, 0));
                    }
                    netDxf.Entities.Polyline pl = new netDxf.Entities.Polyline(Vertices, true);
                    pl.Color = new AciColor(System.Drawing.Color.Blue);
                    dxf.AddEntity(pl);
                }
            }
            if (displayshapes)
            {
                foreach (var a in PLS.DisplayShapes)
                {
                    List <netDxf.Entities.PolylineVertex> Vertices = new List <netDxf.Entities.PolylineVertex>();
                    foreach (var v in a.Vertices)
                    {
                        Vertices.Add(new netDxf.Entities.PolylineVertex(v.X, v.Y, 0));
                    }
                    netDxf.Entities.Polyline pl = new netDxf.Entities.Polyline(Vertices, true);
                    pl.Color = new AciColor(System.Drawing.Color.Green);
                    dxf.AddEntity(pl);
                }
            }
            if (false)
            {
                foreach (var a in PLS.Shapes)
                {
                    List <netDxf.Entities.PolylineVertex> Vertices = new List <netDxf.Entities.PolylineVertex>();
                    foreach (var v in a.Vertices)
                    {
                        Vertices.Add(new netDxf.Entities.PolylineVertex(v.X, v.Y, 0));
                    }
                    netDxf.Entities.Polyline pl = new netDxf.Entities.Polyline(Vertices, true);
                    pl.Color = new AciColor(System.Drawing.Color.Red);
                    dxf.AddEntity(pl);
                }
            }

            // save to file
            dxf.Save(to);
        }
Esempio n. 4
0
        public static bool SaveGerberFileToImage(string GerberFilename, string BitmapFilename, float dpi, Color Foreground, Color Background)
        {
            try
            {
                ParsedGerber      PLS;
                GerberParserState State = new GerberParserState()
                {
                    PreCombinePolygons = false
                };

                var FileType = Gerber.FindFileType(GerberFilename);
                Gerber.DetermineBoardSideAndLayer(GerberFilename, out State.Side, out State.Layer);
                bool forcezero = false;

                if (State.Layer == BoardLayer.Outline)
                {
                    //    PLS.PreCombinePolygons = true;
                    //    forcezero = true;
                }
                if (FileType == BoardFileType.Drill)
                {
                    PLS = PolyLineSet.LoadExcellonDrillFile(GerberFilename);
                }
                else
                {
                    PLS = PolyLineSet.LoadGerberFile(GerberFilename, forcezero, Gerber.WriteSanitized, State);
                }
                double WidthInMM  = PLS.BoundingBox.BottomRight.X - PLS.BoundingBox.TopLeft.X;
                double HeightInMM = PLS.BoundingBox.BottomRight.Y - PLS.BoundingBox.TopLeft.Y;
                int    Width      = (int)(Math.Ceiling((WidthInMM) * (dpi / 25.4)));
                int    Height     = (int)(Math.Ceiling((HeightInMM) * (dpi / 25.4)));

                Console.WriteLine("Progress: Exporting {0} ({2},{3}mm) to {1} ({4},{5})", GerberFilename, BitmapFilename, WidthInMM, HeightInMM, Width, Height);
                GerberImageCreator GIC = new GerberImageCreator();
                GIC.scale = dpi / 25.4f; // dpi
                GIC.BoundingBox.AddBox(PLS.BoundingBox);

                var    Tr = GIC.BuildMatrix(Width, Height);
                Bitmap B2 = GIC.RenderToBitmap(Width, Height, Tr, Foreground, Background, PLS, true);
                if (B2 == null)
                {
                    return(false);
                }
                B2.Save(BitmapFilename);
                return(true);
            }
            catch (Exception E)
            {
                Console.WriteLine("Error: Errors while writing bitmap {0} for gerberfile {1} at dpi {2}:", BitmapFilename, GerberFilename, dpi);
                while (E != null)
                {
                    Console.WriteLine("Error: \t{0}", E.Message);
                    E = E.InnerException;
                }
                return(false);
            }
        }
Esempio n. 5
0
        private void OutlineFileBox_TextChanged(object sender, EventArgs e)
        {
            ParsedGerber PLS         = null;
            string       OutlineFile = OutlineFileBox.Text;

            if (System.IO.File.Exists(OutlineFile) == false)
            {
                return;
            }
            PLS = PolyLineSet.LoadGerberFile(OutlineFile);

            sizebox.Text = String.Format("{0}x{1}mm", PLS.BoundingBox.Width(), PLS.BoundingBox.Height());
        }
Esempio n. 6
0
        public static PolyLineSet.Bounds GetBoundingBox(List <string> generatedFiles)
        {
            PolyLineSet.Bounds A = new PolyLineSet.Bounds();

            foreach (var a in generatedFiles)
            {
                ParsedGerber PLS = PolyLineSet.LoadGerberFile(a, State: new GerberParserState()
                {
                    PreCombinePolygons = false
                });
                A.AddBox(PLS.BoundingBox);
            }
            return(A);
        }
Esempio n. 7
0
        static void Slice(string slicefile, List <string> inputgerbers)
        {
            List <PolyLine> SliceSet = new List <PolyLine>();

            var OutputFolder = Path.GetDirectoryName(slicefile) + @"\Output\" + Path.GetFileNameWithoutExtension(slicefile);

            ParsedGerber P = PolyLineSet.LoadGerberFile(new StandardConsoleLog(), slicefile);

            foreach (var l in P.Shapes)
            {
                /* Polygon Pp = new Polygon();
                *  Pp.Closed = true;
                *  var vertL = from i in l.Vertices select new vec2(i.X, i.Y);
                *  Pp.Vertices.AddRange(vertL);*/
                SliceSet.Add(l);
            }

            int slid = 1;

            foreach (var S in SliceSet)
            {
                Console.WriteLine("Slicing {0}/{1}", slid, SliceSet.Count);
                var SliceOutputFolder = Path.GetDirectoryName(slicefile) + @"\Output\" + Path.GetFileNameWithoutExtension(slicefile) + "\\Slice" + slid.ToString();
                if (Directory.Exists(SliceOutputFolder) == false)
                {
                    Directory.CreateDirectory(SliceOutputFolder);
                }

                foreach (var a in inputgerbers)
                {
                    try
                    {
                        var bf = GerberLibrary.Gerber.FindFileType(a);
                        if (bf == BoardFileType.Gerber)
                        {
                            BoardSide  bs;
                            BoardLayer L;
                            GerberLibrary.Gerber.DetermineBoardSideAndLayer(a, out bs, out L);

                            GerberMerger.WriteContainedOnly(a, S, Path.Combine(SliceOutputFolder + "\\", Path.GetFileName(a)), new StandardConsoleLog());
                        }
                    }
                    catch (Exception) { };
                }
                slid++;
            }
        }
Esempio n. 8
0
        public static bool SaveDebugImage(string GerberFilename, string BitmapFilename, float dpi, Color Foreground, Color Background)
        {
            ParsedGerber      PLS;
            GerberParserState State = new GerberParserState()
            {
                PreCombinePolygons = false
            };

            var FileType = Gerber.FindFileType(GerberFilename);

            Gerber.DetermineBoardSideAndLayer(GerberFilename, out State.Side, out State.Layer);
            bool forcezero = false;

            if (State.Layer == BoardLayer.Outline)
            {
                //    PLS.PreCombinePolygons = true;

                //    forcezero = true;
            }
            if (FileType == BoardFileType.Drill)
            {
                PLS = PolyLineSet.LoadExcellonDrillFile(GerberFilename);
            }
            else
            {
                PLS = PolyLineSet.LoadGerberFile(GerberFilename, forcezero, Gerber.WriteSanitized, State);
            }
            double WidthInMM  = PLS.BoundingBox.BottomRight.X - PLS.BoundingBox.TopLeft.X;
            double HeightInMM = PLS.BoundingBox.BottomRight.Y - PLS.BoundingBox.TopLeft.Y;
            int    Width      = (int)(Math.Ceiling((WidthInMM) * (dpi / 25.4)));
            int    Height     = (int)(Math.Ceiling((HeightInMM) * (dpi / 25.4)));

            Console.WriteLine("Progress: Exporting {0} ({2},{3}mm) to {1} ({4},{5})", GerberFilename, BitmapFilename, WidthInMM, HeightInMM, Width, Height);
            GerberImageCreator GIC = new GerberImageCreator();

            GIC.scale = dpi / 25.4f; // dpi
            GIC.BoundingBox.AddBox(PLS.BoundingBox);

            var Tr = GIC.BuildMatrix(Width, Height);

            Bitmap B2 = GIC.RenderToBitmap(Width, Height, Tr, Foreground, Background, PLS, true);

            if (B2 == null)
            {
                return(false);
            }

            var    GerberLines = PolyLineSet.SanitizeInputLines(System.IO.File.ReadAllLines(GerberFilename).ToList());
            double LastX       = 0;
            double LastY       = 0;



            Graphics G2 = Graphics.FromImage(B2);

            GerberImageCreator.ApplyAASettings(G2);
            //G2.Clear(Background);
            G2.Transform = Tr.Clone();



            foreach (var L in GerberLines)
            {
                if (L[0] != '%')
                {
                    GerberSplitter GS = new GerberSplitter();
                    GS.Split(L, PLS.State.CoordinateFormat);

                    if (GS.Has("G") && (int)GS.Get("G") == 3)
                    {
                        double X = PLS.State.CoordinateFormat.ScaleFileToMM(GS.Get("X"));
                        double Y = PLS.State.CoordinateFormat.ScaleFileToMM(GS.Get("Y"));

                        double I = PLS.State.CoordinateFormat.ScaleFileToMM(GS.Get("I"));
                        double J = PLS.State.CoordinateFormat.ScaleFileToMM(GS.Get("J"));

                        //Console.WriteLine("Counterclockwise Curve {0},{1} -> {2},{3}", LastX, LastY, X, Y);
                        DrawCross(G2, X, Y, Color.Blue);
                        DrawCross(G2, LastX, LastY, Color.Red);

                        DrawCross(G2, LastX + I, LastY - J, Color.Yellow);
                        DrawCross(G2, LastX + I, LastY + J, Color.Purple);
                        DrawCross(G2, LastX - I, LastY - J, Color.Green);
                        DrawCross(G2, LastX - I, LastY + J, Color.Orange);
                    }

                    if (GS.Has("X"))
                    {
                        LastX = PLS.State.CoordinateFormat.ScaleFileToMM(GS.Get("X"));
                    }
                    if (GS.Has("Y"))
                    {
                        LastY = PLS.State.CoordinateFormat.ScaleFileToMM(GS.Get("Y"));
                    }
                }
            }


            B2.Save(BitmapFilename);
            return(true);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            if (args.Count() < 2)
            {
                Console.WriteLine("Usage: GerberToOutline.exe <infile> <outfile>");
                return;
            }

            string infile  = args[0];
            string outfile = args[1];

            var FileType = Gerber.FindFileType(infile);

            if (FileType == BoardFileType.Unsupported)
            {
                if (Gerber.ExtremelyVerbose)
                {
                    Console.WriteLine("Warning: {1}: files with extension {0} are not supported!", Path.GetExtension(infile), Path.GetFileName(infile));
                }
                return;
            }


            ParsedGerber      PLS;
            GerberParserState State = new GerberParserState()
            {
                PreCombinePolygons = false
            };

            if (FileType == BoardFileType.Drill)
            {
                if (Gerber.ExtremelyVerbose)
                {
                    Console.WriteLine("Log: Drill file: {0}", infile);
                }
                PLS = PolyLineSet.LoadExcellonDrillFile(new StandardConsoleLog(), infile, false, 1.0);
                // ExcellonFile EF = new ExcellonFile();
                // EF.Load(a);
            }
            else

            {
                bool forcezerowidth     = false;
                bool precombinepolygons = false;
                if (Gerber.ExtremelyVerbose)
                {
                    Console.WriteLine("Log: Gerber file: {0}", infile);
                }
                BoardSide  Side  = BoardSide.Unknown;
                BoardLayer Layer = BoardLayer.Unknown;
                Gerber.DetermineBoardSideAndLayer(infile, out Side, out Layer);
                if (Layer == BoardLayer.Outline || Layer == BoardLayer.Mill)
                {
                    forcezerowidth     = true;
                    precombinepolygons = true;
                }
                State.PreCombinePolygons = precombinepolygons;

                PLS       = PolyLineSet.LoadGerberFile(new StandardConsoleLog(), infile, forcezerowidth, false, State);
                PLS.Side  = State.Side;
                PLS.Layer = State.Layer;
                if (Layer == BoardLayer.Outline)
                {
                    PLS.FixPolygonWindings();
                }
            }
            SVGGraphicsInterface SG = new SVGGraphicsInterface(PLS.BoundingBox.Width() * 100, PLS.BoundingBox.Height() * 100);

            SG.ScaleTransform(10, 10);
            SG.TranslateTransform((float)-PLS.BoundingBox.TopLeft.X, (float)-PLS.BoundingBox.TopLeft.Y);
            DrawToInterface(PLS, SG);
            SG.Save(outfile);
            System.Diagnostics.Process.Start(outfile);
            Console.WriteLine("press any key to continue..");
            Console.ReadKey();
        }
Esempio n. 10
0
        private static void ConvertFile(string a, bool back)
        {
            string basename = a.Substring(0, a.Length - 4);

            string png     = basename + "Silk.png";
            string goldpng = basename + "Gold.png";

            if (back)
            {
                png     = basename + "BottomSilk.png";
                goldpng = basename + "BottomGold.png";
            }

            Bitmap B  = (Bitmap)Image.FromFile(png);
            Bitmap B2 = null;

            if (System.IO.File.Exists(goldpng))
            {
                B2 = (Bitmap)Image.FromFile(goldpng);
            }

            try
            {
                System.IO.Directory.CreateDirectory(basename);
            }
            catch (Exception)
            {
            }

            string newa = basename + "\\" + System.IO.Path.GetFileName(a);;
            string gko  = basename + ".gko";
            string pnl  = basename + ".pnl";

            if (System.IO.File.Exists(gko) == false && System.IO.File.Exists(pnl) == true)
            {
                gko = pnl;
            }

            string newgko = basename + "\\" + System.IO.Path.GetFileNameWithoutExtension(a) + ".gko";;

            if (System.IO.File.Exists(gko))
            {
                System.IO.File.Copy(gko, newgko, true);
            }

            System.IO.File.Copy(a, newa, true);
            a = newa;

            string p = basename + "/topsilk.gto";

            if (back)
            {
                p = basename + "/bottomsilk.gbo";
            }
            if (back)
            {
                B.RotateFlip(RotateFlipType.RotateNoneFlipX);
            }
            B.RotateFlip(RotateFlipType.RotateNoneFlipY);
            if (B2 != null)
            {
                B2.RotateFlip(RotateFlipType.RotateNoneFlipY);
            }
            if (B != null)
            {
                double Res = 200.0 / 25.4;

                ParsedGerber PLS = null;
                string       f   = basename + ".gko";
                if (System.IO.File.Exists(f))
                {
                    int polyid = 0;
                    PLS = PolyLineSet.LoadGerberFile(f);


                    string bottomcopper     = basename + "/bottomcopper.gbl";
                    string topcopper        = basename + "/topcopper.gtl";
                    string bottomsoldermask = basename + "/bottomsoldermask.gbs";
                    string topsoldermask    = basename + "/topsoldermask.gts";
                    string bottomsilk       = basename + "/bottomsilk.gbo";
                    if (back)
                    {
                        bottomsilk = basename + "/topsilk.gto";
                    }
                    GerberArtWriter GAW3 = new GerberLibrary.GerberArtWriter();
                    GAW3.Write(topsoldermask);

                    GerberArtWriter GAW = new GerberLibrary.GerberArtWriter();
                    PolyLine        PL  = new PolyLine(polyid++);
                    PL.Add(PLS.BoundingBox.TopLeft.X, PLS.BoundingBox.TopLeft.Y);
                    PL.Add(PLS.BoundingBox.BottomRight.X, PLS.BoundingBox.TopLeft.Y);
                    PL.Add(PLS.BoundingBox.BottomRight.X, PLS.BoundingBox.TopLeft.Y + 8);
                    PL.Add(PLS.BoundingBox.TopLeft.X, PLS.BoundingBox.TopLeft.Y + 8);
                    GAW.AddPolygon(PL);


                    PolyLine PL3 = new PolyLine(polyid++);
                    PL3.Add(PLS.BoundingBox.TopLeft.X, PLS.BoundingBox.BottomRight.Y - 8);
                    PL3.Add(PLS.BoundingBox.BottomRight.X, PLS.BoundingBox.BottomRight.Y - 8);
                    PL3.Add(PLS.BoundingBox.BottomRight.X, PLS.BoundingBox.BottomRight.Y);
                    PL3.Add(PLS.BoundingBox.TopLeft.X, PLS.BoundingBox.BottomRight.Y);
                    GAW.AddPolygon(PL3);

                    GAW.Write(bottomsoldermask);


                    GerberArtWriter GAW2 = new GerberLibrary.GerberArtWriter();
                    PolyLine        PL2  = new PolyLine(polyid++);
                    PL2.Add(PLS.BoundingBox.TopLeft.X, PLS.BoundingBox.TopLeft.Y);
                    PL2.Add(PLS.BoundingBox.BottomRight.X, PLS.BoundingBox.TopLeft.Y);
                    PL2.Add(PLS.BoundingBox.BottomRight.X, PLS.BoundingBox.BottomRight.Y);
                    PL2.Add(PLS.BoundingBox.TopLeft.X, PLS.BoundingBox.BottomRight.Y);
                    GAW2.AddPolygon(PL2);
                    GAW2.Write(bottomcopper);

                    if (B2 != null)
                    {
                        GerberLibrary.ArtWork.Functions.WriteBitmapToGerber(topcopper, PLS, Res, B2, -128);
                        GerberLibrary.ArtWork.Functions.WriteBitmapToGerber(topsoldermask, PLS, Res, B2, -128);
                    }
                    else
                    {
                        GAW2.Write(topcopper);
                    }
                }

                GerberLibrary.ArtWork.Functions.WriteBitmapToGerber(p, PLS, Res, B, -128);
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            GerberNumberFormat GNF = new GerberNumberFormat();

            GNF.DigitsAfter  = 3;
            GNF.DigitsBefore = 3;
            GNF.SetMetricMode();

            GerberSplitter GS = new GerberSplitter();

            GS.Split("X-1.15Y-1.9", GNF, true);

            foreach (var a in GS.Pairs)
            {
                Console.WriteLine("{0}:{1} {2}", a.Key, a.Value.Command, a.Value.Number);
            }
            Console.ReadKey();

            if (args.Count() == 0)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("GerberAnalyse <inputfile> <-forcezerowidth> <-dim>");
                return;
            }
            ParsedGerber PLS;
            bool         forcezerowidth = false;
            bool         compact        = false;

            for (int i = 1; i < args.Count(); i++)
            {
                if (args[i] == "-forcezerowidth")
                {
                    forcezerowidth = true;
                }
                if (args[i] == "-dim")
                {
                    compact = true;
                }
            }

            if (Gerber.FindFileType(args[0].ToLower()) == BoardFileType.Drill)
            {
                PLS = PolyLineSet.LoadExcellonDrillFile(args[0]);
                // ExcellonFile EF = new ExcellonFile();
                // EF.Load(a);
            }
            else
            {
                // PLS.PreCombinePolygons = false;
                // forcezerowidth = true;
                PLS = PolyLineSet.LoadGerberFile(args[0], forcezerowidth, false, new GerberParserState()
                {
                    PreCombinePolygons = false
                });
            }

            PLS.CalcPathBounds();

            if (compact)
            {
                CultureInfo CI = CultureInfo.InvariantCulture;

                Console.WriteLine("{0}x{1}(mm)", (PLS.BoundingBox.BottomRight.X - PLS.BoundingBox.TopLeft.X).ToString("N3", CI), (PLS.BoundingBox.BottomRight.Y - PLS.BoundingBox.TopLeft.Y).ToString("N3", CI));
                Console.WriteLine("{0}x{1}(imp)", ((PLS.BoundingBox.BottomRight.X - PLS.BoundingBox.TopLeft.X) / 25.4).ToString("N3", CI), ((PLS.BoundingBox.BottomRight.Y - PLS.BoundingBox.TopLeft.Y) / 25.4).ToString("N3", CI));
            }
            else
            {
                Console.WriteLine("Report for {0}:", args[0]);
                Console.WriteLine("Suspected file side: {0}, layertype: {1}", PLS.Side.ToString(), PLS.Layer.ToString());
                Console.WriteLine("DisplayShape #: {0}", PLS.DisplayShapes.Count);
                foreach (var o in PLS.DisplayShapes)
                {
                    Console.WriteLine("\tOutline {0} vertices thin:{1}", o.Vertices.Count, o.Thin);
                    foreach (var v in o.Vertices)
                    {
                        Console.WriteLine("\t\t{0}", v);
                    }
                }

                Console.WriteLine("OutlineShape #: {0}", PLS.OutlineShapes.Count);
                foreach (var o in PLS.OutlineShapes)
                {
                    Console.WriteLine("\tOutline {0} vertices thin:{1}", o.Vertices.Count, o.Thin);
                    foreach (var v in o.Vertices)
                    {
                        Console.WriteLine("\t\t{0}", v);
                    }
                }
                Console.WriteLine("Aperture #: {0}", PLS.State.Apertures.Count);
                foreach (var apt in PLS.State.Apertures)
                {
                    Console.Write("\tAperture D{0} ", apt.Key.ToString("D2"));
                    Console.Write("type: {0} ", apt.Value.ShapeType.ToString());
                    switch (apt.Value.ShapeType)
                    {
                    case GerberApertureShape.Circle:

                        Console.Write("diameter {0} ", apt.Value.CircleRadius * 2); break;
                    }
                    Console.WriteLine();
                }
                Console.WriteLine("Corners: ");
                Console.WriteLine(PLS.BoundingBox.TopLeft);
                Console.WriteLine(PLS.BoundingBox.BottomRight);
                Console.WriteLine("Size: {0}x{1} mm", PLS.BoundingBox.BottomRight.X - PLS.BoundingBox.TopLeft.X, PLS.BoundingBox.BottomRight.Y - PLS.BoundingBox.TopLeft.Y);
            }
            //  Console.WriteLine("Press any key to continue");
            //  Console.ReadKey();
        }
Esempio n. 12
0
        public static void Subtract(ProgressLog log, string inputfile, string subtractfile, string outputfile)
        {
            log.PushActivity("Subtracting gerbers");
            ParsedGerber inp = PolyLineSet.LoadGerberFile(new StandardConsoleLog(), inputfile, false, false, new GerberParserState()
            {
                GenerateGeometry = false
            });
            ParsedGerber subtr = PolyLineSet.LoadGerberFile(new StandardConsoleLog(), subtractfile, false, false, new GerberParserState()
            {
                GenerateGeometry = false
            });

            var inph = inp.GetApertureHashTable();
            var subh = subtr.GetApertureHashTable();
            Dictionary <string, Tuple <GerberApertureType, List <PointD> > > OverlapList = new Dictionary <string, Tuple <GerberApertureType, List <PointD> > >();

            foreach (var a in inph)
            {
                if (subh.ContainsKey(a.Key))
                {
                    Console.WriteLine("found matching aperture: {0} -> {1}", a.Value, subh[a.Key]);
                    OverlapList[a.Key] = new Tuple <GerberApertureType, List <PointD> >(a.Value, new List <PointD>());
                }
            }

            OverlapList = FillOverlapList(log, OverlapList, subtr, subtractfile);
            List <String> lines    = new List <string>();
            List <String> outlines = new List <string>();

            int  CurrentAperture = 10;
            bool WriteMove       = false;
            int  moveswritten    = 0;

            using (StreamReader sr = new StreamReader(inputfile))
            {
                while (sr.EndOfStream == false)
                {
                    String line = sr.ReadLine();
                    if (line.Length > 0)
                    {
                        lines.Add(line);
                    }
                }
            }
            lines = PolyLineSet.SanitizeInputLines(lines);

            ParsedGerber Parsed = inp;// PolyLineSet.ParseGerber274x(log, lines, true, false, new GerberParserState() { GenerateGeometry = false });

            if (Gerber.ShowProgress)
            {
                log.AddString("found apertures: ");
                foreach (var a in Parsed.State.Apertures)
                {
                    log.AddString(a.Value.ToString());
                }
            }



            GerberNumberFormat CoordinateFormat = new GerberNumberFormat();

            CoordinateFormat.SetImperialMode();
            //   CoordinateFormat = Parsed.State.CoordinateFormat;

            int  cur          = 0;
            bool formatparsed = false;

            while (cur < lines.Count && formatparsed == false)
            {
                if (lines[cur].Length >= 2 && lines[cur].Substring(0, 2) == "%F")
                {
                    CoordinateFormat.Parse(lines[cur]);
                    formatparsed = true;
                }
                cur++;
            }

            //  double coordmultiplier = 1.0;
            double LastX = 0;
            double LastY = 0;

            for (int i = 0; i < lines.Count; i++)
            {
                GerberSplitter GS           = new GerberSplitter();
                string         FinalLine    = lines[i].Replace("%", "").Replace("*", "").Trim();
                bool           DumpToOutput = false;
                bool           metaopen     = false;
                if (lines[i][0] == '%')
                {
                    DumpToOutput = true;
                    metaopen     = true;
                }
                else
                {
                    GS.Split(lines[i], CoordinateFormat);
                }


                switch (FinalLine)
                {
                case "G71": CoordinateFormat.SetMetricMode(); break;

                case "G70": CoordinateFormat.SetImperialMode(); break;

                case "MOIN":
                {
                    CoordinateFormat.SetImperialMode();
                    //CoordinateFormat.Multiplier  = 25.4f;
                }
                break;

                case "MOMM":
                {
                    CoordinateFormat.SetMetricMode();
                    //CoordinateFormat.Multiplier = 1.0f;
                }
                break;
                }
                if (lines[i].Length > 3 && lines[i].Substring(0, 3) == "%AM")
                {
                    string name = lines[i].Substring(3).Split('*')[0];

                    var M = Parsed.State.ApertureMacros[name];
                    M.Written = true;
                    var gerb = M.BuildGerber(CoordinateFormat, 0, "").Split('\n');
                    foreach (var l in gerb)
                    {
                        if (l.Trim().Length > 0)
                        {
                            outlines.Add(l.Trim());
                        }
                    }
                    //    outlines.Add(lines[i]);
                    //  if (lines[i][lines[i].Length - 1] != '%')
                    ///  {
                    //   i++;
                    while (lines[i][lines[i].Length - 1] != '%')
                    {
                        //     outlines.Add(lines[i]);
                        i++;
                    }
                    //                       outlines.Add(lines[i]);
                    //     }
                }
                else

                if (lines[i].Length > 3 && lines[i].Substring(0, 3) == "%AD")
                {
                    GCodeCommand GCC = new GCodeCommand();
                    GCC.Decode(lines[i], CoordinateFormat);
                    if (GCC.numbercommands.Count < 1)
                    {
                        log.AddString(String.Format("Skipping bad aperture definition: {0}", lines[i]));
                    }
                    else
                    {
                        int ATID     = (int)GCC.numbercommands[0];
                        var Aperture = Parsed.State.Apertures[ATID];
                        if (Gerber.ShowProgress)
                        {
                            log.AddString(String.Format("found " + Aperture.ToString()));
                        }
                        string gerb = Aperture.BuildGerber(CoordinateFormat, "", 0);

                        if ((Aperture.ShapeType == GerberApertureShape.Compound || Aperture.ShapeType == GerberApertureShape.Macro) && Parsed.State.ApertureMacros[Aperture.MacroName].Written == false)
                        {
                            log.AddString(String.Format("Macro type defined - skipping"));
                        }
                        else
                        {
                            outlines.Add(gerb);
                        }

                        //                   outlines.Add(lines[i]);
                        if (lines[i][lines[i].Length - 1] != '%')
                        {
                            i++;
                            while (lines[i] != "%")
                            {
                                //                         outlines.Add(lines[i]);
                                i++;
                            }
                            //                   outlines.Add(lines[i]);
                        }
                    }
                }
                else
                {
                    bool PureD = false;
                    if (GS.Has("G"))
                    {
                        int GCode = (int)GS.Get("G");
                        switch (GCode)
                        {
                        case 4: DumpToOutput = true; break;

                        case 90: CoordinateFormat.Relativemode = false; break;

                        case 91: CoordinateFormat.Relativemode = true; break;

                        case 71: CoordinateFormat.Multiplier = 1.0d; break;

                        case 70: CoordinateFormat.Multiplier = 25.4d; break;
                        }
                    }
                    if (DumpToOutput)
                    {
                        outlines.Add(lines[i]);
                        if (lines[i].Contains("LNData"))
                        {
                            log.AddString(String.Format(" heh"));
                        }
                        if (lines[i][0] == '%')
                        {
                            int starti = i;
                            if (lines[i].Length == 1)
                            {
                                i++;
                            }
                            while (lines[i][lines[i].Length - 1] != '%')
                            {
                                if (i > starti)
                                {
                                    outlines.Add(lines[i]);
                                }
                                i++;
                            }
                            if (i > starti)
                            {
                                outlines.Add(lines[i]);
                            }
                        }
                    }
                    else
                    {
                        bool translate = true;
                        if (CoordinateFormat.Relativemode)
                        {
                            translate = false;
                        }
                        if (GS.Has("X") == false && GS.Has("Y") == false && (GS.Has("D") && GS.Get("D") < 10))
                        {
                            PureD = true;
                            int Dcode = (int)GS.Get("D");
                            if (Dcode == 1 || Dcode == 3)
                            {
                                if (moveswritten == 0)
                                {
                                    WriteMove = true;
                                }
                            }
                            moveswritten++;
                            //log.AddString(String.Format("Pure D Code: {0}", lines[i]));
                        }
                        else
                        if (GS.Has("X") || GS.Has("Y") || (GS.Has("D") && GS.Get("D") < 10))
                        {
                            int Dcode = (int)GS.Get("D");
                            if (Dcode == 1 || Dcode == 3)
                            {
                                if (moveswritten == 0)
                                {
                                    WriteMove = true;
                                }
                            }
                            moveswritten++;
                            double X = LastX;
                            if (GS.Has("X"))
                            {
                                X = GS.Get("X");
                            }
                            double Y = LastY;
                            if (GS.Has("Y"))
                            {
                                Y = GS.Get("Y");
                            }
                            LastX = X;
                            LastY = Y;

                            GS.Set("X", X);
                            GS.Set("Y", Y);
                        }
                        if (GS.Get("D") >= 10)
                        {
                            CurrentAperture = (int)GS.Get("D");
                            // Select Aperture;
                        }
                        string hash      = inp.State.Apertures[CurrentAperture].GetApertureHash();
                        bool   writeline = true;
                        if (OverlapList.ContainsKey(hash) && ((int)GS.Get("D") == 3 || (int)GS.Get("D") == 1))
                        {
                            PointD n = new PointD(LastX, LastY);
                            if (OverlapList[hash].Item2.Contains(n))
                            {
//                                Console.WriteLine("eliminate this!");
                                GS.Set("D", 2);
                            }
//                            Console.WriteLine("Potential Skipping Segment Found!");
                        }
                        if (WriteMove)
                        {
                            GerberSplitter GS2 = new GerberSplitter();
                            GS2.Set("D", 2);
                            double X0 = 0;
                            double Y0 = 0;
                            //GetTransformedCoord(DX, DY, DXp, DYp, Angle, CA, SA, CoordinateFormat, translate, ref X0, ref Y0);
                            GS2.Set("X", X0);
                            GS2.Set("Y", Y0);
                            WriteMove = false;
                            outlines.Add(GS2.Rebuild(CoordinateFormat));
                        }
                        outlines.Add(GS.Rebuild(CoordinateFormat));
                        if (PureD)
                        {
                            //log.AddString(String.Format("pureD"));
                        }
                    }
                }
            }
            try
            {
                List <String> PostProcLines = new List <string>();
                foreach (var a in outlines)
                {
                    if (a == "%")
                    {
                        PostProcLines[PostProcLines.Count - 1] += "%";
                    }
                    else
                    {
                        PostProcLines.Add(a);
                    }
                }
                Gerber.WriteAllLines(outputfile, PolyLineSet.SanitizeInputLines(PostProcLines));
            }
            catch (Exception E)
            {
                log.AddString(String.Format(E.Message));
            }
            log.PopActivity();
        }
Esempio n. 13
0
        private List <Shape> LoadGerber(string Path)
        {
            BoardFileType FileType = Gerber.FindFileType(Path);

            if (FileType == BoardFileType.Unsupported)
            {
                return(null);
            }

            ParsedGerber      PLS;
            GerberParserState State = new GerberParserState()
            {
                PreCombinePolygons = false
            };

            if (FileType == BoardFileType.Drill)
            {
                PLS = PolyLineSet.LoadExcellonDrillFile(Path, false, 1.0);
            }
            else
            {
                bool forcezerowidth     = false;
                bool precombinepolygons = false;

                BoardSide  Side  = BoardSide.Unknown;
                BoardLayer Layer = BoardLayer.Unknown;
                Gerber.DetermineBoardSideAndLayer(Path, out Side, out Layer);

                if (Layer == BoardLayer.Outline || Layer == BoardLayer.Mill)
                {
                    forcezerowidth     = true;
                    precombinepolygons = true;
                }
                State.PreCombinePolygons = precombinepolygons;

                PLS       = PolyLineSet.LoadGerberFile(Path, forcezerowidth, false, State);
                PLS.Side  = State.Side;
                PLS.Layer = State.Layer;

                if (Layer == BoardLayer.Outline)
                {
                    PLS.FixPolygonWindings();
                }
            }

            //Convert the gerber polygons into a generic shape list used by other functions
            List <Shape> retShape = new List <Shape>();

            foreach (var shape in PLS.DisplayShapes)
            {
                Shape tempShape = new Shape();

                tempShape.Vertices = new List <Vector2d>();

                for (int i = 0; i < shape.Vertices.Count; i++)
                {
                    tempShape.Vertices.Add(new Vector2d(shape.Vertices[i].X, shape.Vertices[i].Y));
                }

                retShape.Add(tempShape);
            }

            return(retShape);
        }