Beispiel #1
0
 internal Layouts(DxfDocument document)
     : this(document, null)
 {
 }
        public void Write(Stream stream, DxfDocument document, bool binary)
        {
            this.doc = document;
            this.isBinary = binary;

            if (this.doc.DrawingVariables.AcadVer < DxfVersion.AutoCad2000)
                throw new NotSupportedException("Only AutoCad2000 and newer dxf versions are supported.");

            this.encodedStrings = new Dictionary<string, string>();

            // create the default PaperSpace layout in case it does not exist. The ModelSpace layout always exists
            if (this.doc.Layouts.Count == 1)
                this.doc.Layouts.Add(new Layout("Layout1"));

            // create the application registry AcCmTransparency in case it doesn't exists, it is required by the layer and entity transparency
            this.doc.ApplicationRegistries.Add(new ApplicationRegistry("AcCmTransparency"));

            // create the application registry GradientColor1ACI and GradientColor2ACI in case they don't exists , they are required by the hatch gradient pattern
            this.doc.ApplicationRegistries.Add(new ApplicationRegistry("GradientColor1ACI"));
            this.doc.ApplicationRegistries.Add(new ApplicationRegistry("GradientColor2ACI"));

            // dictionaries
            List<DictionaryObject> dictionaries = new List<DictionaryObject>();

            // Named dictionary it is always the first to appear in the object section
            DictionaryObject namedObjectDictionary = new DictionaryObject(this.doc);
            this.doc.NumHandles = namedObjectDictionary.AsignHandle(this.doc.NumHandles);
            dictionaries.Add(namedObjectDictionary);

            // create the Group dictionary, this dictionary always appear even if there are no groups in the drawing
            DictionaryObject groupDictionary = new DictionaryObject(namedObjectDictionary);
            this.doc.NumHandles = groupDictionary.AsignHandle(this.doc.NumHandles);
            foreach (Group group in this.doc.Groups.Items)
            {
                groupDictionary.Entries.Add(group.Handle, group.Name);
            }
            dictionaries.Add(groupDictionary);
            namedObjectDictionary.Entries.Add(groupDictionary.Handle, DxfObjectCode.GroupDictionary);

            // Layout dictionary
            DictionaryObject layoutDictionary = new DictionaryObject(namedObjectDictionary);
            this.doc.NumHandles = layoutDictionary.AsignHandle(this.doc.NumHandles);
            if (this.doc.Layouts.Count > 0)
            {
                foreach (Layout layout in this.doc.Layouts.Items)
                {
                    layoutDictionary.Entries.Add(layout.Handle, layout.Name);
                }
                dictionaries.Add(layoutDictionary);
                namedObjectDictionary.Entries.Add(layoutDictionary.Handle, DxfObjectCode.LayoutDictionary);
            }

            // create the Underlay definitions dictionary
            DictionaryObject dgnDefinitionDictionary = new DictionaryObject(namedObjectDictionary);
            this.doc.NumHandles = dgnDefinitionDictionary.AsignHandle(this.doc.NumHandles);
            if (this.doc.UnderlayDgnDefinitions.Count > 0)
            {
                foreach (UnderlayDgnDefinition underlayDef in this.doc.UnderlayDgnDefinitions.Items)
                {
                    dgnDefinitionDictionary.Entries.Add(underlayDef.Handle, underlayDef.Name);
                    dictionaries.Add(dgnDefinitionDictionary);
                    namedObjectDictionary.Entries.Add(dgnDefinitionDictionary.Handle, DxfObjectCode.UnderlayDgnDefinitionDictionary);
                }
            }
            DictionaryObject dwfDefinitionDictionary = new DictionaryObject(namedObjectDictionary);
            this.doc.NumHandles = dwfDefinitionDictionary.AsignHandle(this.doc.NumHandles);
            if (this.doc.UnderlayDwfDefinitions.Count > 0)
            {
                foreach (UnderlayDwfDefinition underlayDef in this.doc.UnderlayDwfDefinitions.Items)
                {
                    dwfDefinitionDictionary.Entries.Add(underlayDef.Handle, underlayDef.Name);
                    dictionaries.Add(dwfDefinitionDictionary);
                    namedObjectDictionary.Entries.Add(dwfDefinitionDictionary.Handle, DxfObjectCode.UnderlayDwfDefinitionDictionary);
                }
            }
            DictionaryObject pdfDefinitionDictionary = new DictionaryObject(namedObjectDictionary);
            this.doc.NumHandles = pdfDefinitionDictionary.AsignHandle(this.doc.NumHandles);
            if (this.doc.UnderlayPdfDefinitions.Count > 0)
            {
                foreach (UnderlayPdfDefinition underlayDef in this.doc.UnderlayPdfDefinitions.Items)
                {
                    pdfDefinitionDictionary.Entries.Add(underlayDef.Handle, underlayDef.Name);
                    dictionaries.Add(pdfDefinitionDictionary);
                    namedObjectDictionary.Entries.Add(pdfDefinitionDictionary.Handle, DxfObjectCode.UnderlayPdfDefinitionDictionary);
                }
            }

            // create the MLine style dictionary
            DictionaryObject mLineStyleDictionary = new DictionaryObject(namedObjectDictionary);
            this.doc.NumHandles = mLineStyleDictionary.AsignHandle(this.doc.NumHandles);
            if (this.doc.MlineStyles.Count > 0)
            {
                foreach (MLineStyle mLineStyle in this.doc.MlineStyles.Items)
                {
                    mLineStyleDictionary.Entries.Add(mLineStyle.Handle, mLineStyle.Name);
                }
                dictionaries.Add(mLineStyleDictionary);
                namedObjectDictionary.Entries.Add(mLineStyleDictionary.Handle, DxfObjectCode.MLineStyleDictionary);
            }

            // create the image dictionary
            DictionaryObject imageDefDictionary = new DictionaryObject(namedObjectDictionary);
            this.doc.NumHandles = imageDefDictionary.AsignHandle(this.doc.NumHandles);
            if (this.doc.ImageDefinitions.Count > 0)
            {
                foreach (ImageDefinition imageDef in this.doc.ImageDefinitions.Items)
                {
                    imageDefDictionary.Entries.Add(imageDef.Handle, imageDef.Name);
                }

                dictionaries.Add(imageDefDictionary);

                namedObjectDictionary.Entries.Add(imageDefDictionary.Handle, DxfObjectCode.ImageDefDictionary);
                namedObjectDictionary.Entries.Add(this.doc.RasterVariables.Handle, DxfObjectCode.ImageVarsDictionary);
            }

            this.doc.DrawingVariables.HandleSeed = this.doc.NumHandles.ToString("X");

            this.Open(stream, this.doc.DrawingVariables.AcadVer < DxfVersion.AutoCad2007 ? Encoding.Default : null);

            // The comment group, 999, is not used in binary DXF files.
            if (!this.isBinary)
            {
                foreach (string comment in this.doc.Comments)
                    this.WriteComment(comment);
            }

            //HEADER SECTION
            this.BeginSection(DxfObjectCode.HeaderSection);
            foreach (HeaderVariable variable in this.doc.DrawingVariables.Values)
            {
                this.WriteSystemVariable(variable);
            }
            // writing a copy of the active dimension style variables in the header section will avoid to be displayed as <style overrides> in AutoCad
            DimensionStyle activeDimStyle;
             if(this.doc.DimensionStyles.TryGetValue(this.doc.DrawingVariables.DimStyle, out activeDimStyle))
                 this.WriteActiveDimensionStyleSystemVaribles(activeDimStyle);
            this.EndSection();

            //CLASSES SECTION
            this.BeginSection(DxfObjectCode.ClassesSection);
            this.WriteRasterVariablesClass(1);
            if (this.doc.ImageDefinitions.Items.Count > 0)
            {
                this.WriteImageDefClass(this.doc.ImageDefinitions.Count);
                this.WriteImageDefRectorClass(this.doc.Images.Count);
                this.WriteImageClass(this.doc.Images.Count);
            }
            this.EndSection();

            //TABLES SECTION
            this.BeginSection(DxfObjectCode.TablesSection);

            //registered application tables
            this.BeginTable(this.doc.ApplicationRegistries.CodeName, (short) this.doc.ApplicationRegistries.Count, this.doc.ApplicationRegistries.Handle);
            foreach (ApplicationRegistry id in this.doc.ApplicationRegistries.Items)
            {
                this.WriteApplicationRegistry(id);
            }
            this.EndTable();

            //viewport tables
            this.BeginTable(this.doc.VPorts.CodeName, (short) this.doc.VPorts.Count, this.doc.VPorts.Handle);
            foreach (VPort vport in this.doc.VPorts)
            {
                this.WriteVPort(vport);
            }
            this.EndTable();

            //line type tables
            //The LTYPE table always precedes the LAYER table. I guess because the layers reference the line types,
            //why this same rule is not applied to DIMSTYLE tables is a mystery, since they also reference text styles and block records
            this.BeginTable(this.doc.LineTypes.CodeName, (short) this.doc.LineTypes.Count, this.doc.LineTypes.Handle);
            foreach (LineType lineType in this.doc.LineTypes.Items)
            {
                this.WriteLineType(lineType);
            }
            this.EndTable();

            //layer tables
            this.BeginTable(this.doc.Layers.CodeName, (short) this.doc.Layers.Count, this.doc.Layers.Handle);
            foreach (Layer layer in this.doc.Layers.Items)
            {
                this.WriteLayer(layer);
            }
            this.EndTable();

            //text style tables
            this.BeginTable(this.doc.TextStyles.CodeName, (short) this.doc.TextStyles.Count, this.doc.TextStyles.Handle);
            foreach (TextStyle style in this.doc.TextStyles.Items)
            {
                this.WriteTextStyle(style);
            }
            this.EndTable();

            //dimension style tables
            this.BeginTable(this.doc.DimensionStyles.CodeName, (short) this.doc.DimensionStyles.Count, this.doc.DimensionStyles.Handle);
            foreach (DimensionStyle style in this.doc.DimensionStyles.Items)
            {
                this.WriteDimensionStyle(style);
            }
            this.EndTable();

            //view
            this.BeginTable(this.doc.Views.CodeName, (short)this.doc.Views.Count, this.doc.Views.Handle);
            this.EndTable();

            //UCS
            this.BeginTable(this.doc.UCSs.CodeName, (short) this.doc.UCSs.Count, this.doc.UCSs.Handle);
            foreach (UCS ucs in this.doc.UCSs.Items)
            {
                this.WriteUCS(ucs);
            }
            this.EndTable();

            //block record table
            this.BeginTable(this.doc.Blocks.CodeName, (short) this.doc.Blocks.Count, this.doc.Blocks.Handle);
            foreach (Block block in this.doc.Blocks.Items)
            {
                this.WriteBlockRecord(block.Record);
            }
            this.EndTable();

            this.EndSection(); //End section tables

            //BLOCKS SECTION
            this.BeginSection(DxfObjectCode.BlocksSection);
            foreach (Block block in this.doc.Blocks.Items)
            {
                Layout layout = null;
                if (block.Name.StartsWith(Block.DefaultPaperSpaceName))
                {
                    // the entities of the layouts associated with the blocks "*Paper_Space0", "*Paper_Space1",... are included in the Blocks Section
                    string index = block.Name.Remove(0, 12);
                    if (!string.IsNullOrEmpty(index))
                    {
                        layout = block.Record.Layout;
                    }
                }
                this.WriteBlock(block, layout);
            }
            this.EndSection(); //End section blocks

            //ENTITIES SECTION
            this.BeginSection(DxfObjectCode.EntitiesSection);
            foreach (Layout layout in this.doc.Layouts)
            {
                if (!layout.IsPaperSpace) 
                {
                    // ModelSpace
                    List<DxfObject> entities = this.doc.Layouts.GetReferences(layout);
                    foreach (DxfObject o in entities)
                    {
                        this.WriteEntity(o as EntityObject, layout);
                    }
                }
                else if (layout.AssociatedBlock.Name.StartsWith(Block.DefaultPaperSpaceName))
                {
                    // only the entities of the layout associated with the block "*Paper_Space" are included in the Entities Section
                    string index = layout.AssociatedBlock.Name.Remove(0, 12);
                    if (string.IsNullOrEmpty(index))
                    {
                        this.WriteEntity(layout.Viewport, layout);
                        List<DxfObject> entities = this.doc.Layouts.GetReferences(layout);
                        foreach (DxfObject o in entities)
                        {
                            this.WriteEntity(o as EntityObject, layout);
                        }
                    }
                }
            }
            this.EndSection(); //End section entities

            //OBJECTS SECTION
            this.BeginSection(DxfObjectCode.ObjectsSection);

            foreach (DictionaryObject dictionary in dictionaries)
            {
                this.WriteDictionary(dictionary);
            }

            foreach (Group group in this.doc.Groups.Items)
            {
                this.WriteGroup(group, groupDictionary.Handle);
            }

            foreach (Layout layout in this.doc.Layouts)
            {
                this.WriteLayout(layout, layoutDictionary.Handle);
            }

            foreach (MLineStyle style in this.doc.MlineStyles.Items)
            {
                this.WriteMLineStyle(style, mLineStyleDictionary.Handle);
            }

            foreach (UnderlayDgnDefinition underlayDef in this.doc.UnderlayDgnDefinitions.Items)
            {
                this.WriteUnderlayDefinition(underlayDef, dgnDefinitionDictionary.Handle);
            }
            foreach (UnderlayDwfDefinition underlayDef in this.doc.UnderlayDwfDefinitions.Items)
            {
                this.WriteUnderlayDefinition(underlayDef, dwfDefinitionDictionary.Handle);
            }
            foreach (UnderlayPdfDefinition underlayDef in this.doc.UnderlayPdfDefinitions.Items)
            {
                this.WriteUnderlayDefinition(underlayDef, pdfDefinitionDictionary.Handle);
            }

            // the raster variables dictionary is only needed when the drawing has image entities
            if (this.doc.ImageDefinitions.Count > 0)
            {
                this.WriteRasterVariables(this.doc.RasterVariables, imageDefDictionary.Handle);
                foreach (ImageDefinition imageDef in this.doc.ImageDefinitions.Items)
                {
                    foreach (ImageDefinitionReactor reactor in imageDef.Reactors.Values)
                    {
                        this.WriteImageDefReactor(reactor);
                    }
                    this.WriteImageDef(imageDef, imageDefDictionary.Handle);
                }
            }
                
            this.EndSection(); //End section objects

            this.Close();

            stream.Position = 0;
        }
        /// <summary>
        /// Processes a tlog to get the offsets - creates dxf of data
        /// </summary>
        /// <param name="fn">Filename</param>
        /// <returns>Offsets</returns>
        public static double[] getOffsets(string fn, int throttleThreshold = 0)
        {
            // based off tridge's work
            string logfile = fn;

            // old method
            float minx = 0;
            float maxx = 0;
            float miny = 0;
            float maxy = 0;
            float minz = 0;
            float maxz = 0;

            // this is for a dxf
            Polyline3dVertex        vertex;
            List <Polyline3dVertex> vertexes = new List <Polyline3dVertex>();

            // data storage
            Tuple <float, float, float>         offset = new Tuple <float, float, float>(0, 0, 0);
            List <Tuple <float, float, float> > data   = new List <Tuple <float, float, float> >();

            Hashtable filter = new Hashtable();

            // track data to use
            bool useData = false;

            log.Info("Start log: " + DateTime.Now);

            MAVLink mine = new MAVLink();

            mine.logplaybackfile = new BinaryReader(File.Open(logfile, FileMode.Open, FileAccess.Read, FileShare.Read));
            mine.logreadmode     = true;

            mine.packets.Initialize();     // clear

            // gather data
            while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
            {
                byte[] packetraw = mine.readPacket();

                var packet = mine.DebugPacket(packetraw, false);

                // this is for packets we dont know about
                if (packet == null)
                {
                    continue;
                }

                if (packet.GetType() == typeof(MAVLink.mavlink_vfr_hud_t))
                {
                    if (((MAVLink.mavlink_vfr_hud_t)packet).throttle >= throttleThreshold)
                    {
                        useData = true;
                    }
                    else
                    {
                        useData = false;
                    }
                }

                if (packet.GetType() == typeof(MAVLink.mavlink_sensor_offsets_t))
                {
                    offset = new Tuple <float, float, float>(
                        ((MAVLink.mavlink_sensor_offsets_t)packet).mag_ofs_x,
                        ((MAVLink.mavlink_sensor_offsets_t)packet).mag_ofs_y,
                        ((MAVLink.mavlink_sensor_offsets_t)packet).mag_ofs_z);
                }
                else if (packet.GetType() == typeof(MAVLink.mavlink_raw_imu_t) && useData)
                {
                    int div = 20;

                    // fox dxf
                    vertex = new Polyline3dVertex(new Vector3f(
                                                      ((MAVLink.mavlink_raw_imu_t)packet).xmag - offset.Item1,
                                                      ((MAVLink.mavlink_raw_imu_t)packet).ymag - offset.Item2,
                                                      ((MAVLink.mavlink_raw_imu_t)packet).zmag - offset.Item3)
                                                  );
                    vertexes.Add(vertex);


                    // for old method
                    setMinorMax(((MAVLink.mavlink_raw_imu_t)packet).xmag - offset.Item1, ref minx, ref maxx);
                    setMinorMax(((MAVLink.mavlink_raw_imu_t)packet).ymag - offset.Item2, ref miny, ref maxy);
                    setMinorMax(((MAVLink.mavlink_raw_imu_t)packet).zmag - offset.Item3, ref minz, ref maxz);

                    // for new lease sq
                    string item = (int)(((MAVLink.mavlink_raw_imu_t)packet).xmag / div) + "," +
                                  (int)(((MAVLink.mavlink_raw_imu_t)packet).ymag / div) + "," +
                                  (int)(((MAVLink.mavlink_raw_imu_t)packet).zmag / div);

                    if (filter.ContainsKey(item))
                    {
                        filter[item] = (int)filter[item] + 1;

                        if ((int)filter[item] > 3)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        filter[item] = 1;
                    }


                    data.Add(new Tuple <float, float, float>(
                                 ((MAVLink.mavlink_raw_imu_t)packet).xmag - offset.Item1,
                                 ((MAVLink.mavlink_raw_imu_t)packet).ymag - offset.Item2,
                                 ((MAVLink.mavlink_raw_imu_t)packet).zmag - offset.Item3));
                }
            }

            log.Info("Log Processed " + DateTime.Now);

            Console.WriteLine("Extracted " + data.Count + " data points");
            Console.WriteLine("Current offset: " + offset);

            mine.logreadmode = false;
            mine.logplaybackfile.Close();
            mine.logplaybackfile = null;

            if (data.Count < 10)
            {
                CustomMessageBox.Show("Log does not contain enough data");
                throw new Exception("Not Enough Data");
            }

            double[] x = LeastSq(data);

            System.Console.WriteLine("Old Method {0} {1} {2}", -(maxx + minx) / 2, -(maxy + miny) / 2, -(maxz + minz) / 2);

            log.Info("Least Sq Done " + DateTime.Now);

            // create a dxf for those who want to "see" the calibration
            DxfDocument dxf = new DxfDocument();

            Polyline3d polyline = new Polyline3d(vertexes, true);

            polyline.Layer             = new Layer("polyline3d");
            polyline.Layer.Color.Index = 24;
            dxf.AddEntity(polyline);

            Point pnt = new Point(new Vector3f(-offset.Item1, -offset.Item2, -offset.Item3));

            pnt.Layer             = new Layer("old offset");
            pnt.Layer.Color.Index = 22;
            dxf.AddEntity(pnt);

            pnt                   = new Point(new Vector3f(-(float)x[0], -(float)x[1], -(float)x[2]));
            pnt.Layer             = new Layer("new offset");
            pnt.Layer.Color.Index = 21;
            dxf.AddEntity(pnt);

            dxf.Save("magoffset.dxf", DxfVersion.AutoCad2000);

            log.Info("dxf Done " + DateTime.Now);

            Array.Resize <double>(ref x, 3);

            return(x);
        }
 internal DrawingEntities(DxfDocument document)
 {
     this.document     = document;
     this.activeLayout = Layout.ModelSpaceName;
 }
Beispiel #5
0
 internal Groups(DxfDocument document)
     : this(document, null)
 {
 }
 internal ImageDefinitions(DxfDocument document, string handle = null)
     : this(document, 0, handle)
 {
 }
        /// <summary>
        /// Saves a block to a dxf file.
        /// </summary>
        /// <param name="file">Dxf file name.</param>
        /// <param name="version">Version of the dxf database version.</param>
        /// <param name="isBinary">Defines if the file will be saved as binary, by default it will be saved as text</param>
        /// <returns>Return true if the file has been successfully save, false otherwise.</returns>
        public bool Save(string file, DxfVersion version, bool isBinary = false)
        {
            DxfDocument dwg = new DxfDocument(version);
            dwg.DrawingVariables.InsBase = this.origin;
            dwg.DrawingVariables.InsUnits = this.Record.Units;

            foreach (EntityObject entity in this.entities)
                dwg.AddEntity((EntityObject)entity.Clone());

            foreach (AttributeDefinition attdef in this.attributes.Values)
                dwg.AddEntity((EntityObject)attdef.Clone());

            return dwg.Save(file, isBinary);
        }
Beispiel #8
0
        /// <summary>
        /// Creates a block from the content of a <see cref="DxfDocument">document</see>.
        /// </summary>
        /// <param name="doc">A <see cref="DxfDocument">DxfDocument</see> instance.</param>
        /// <param name="name">Name of the new block.</param>
        /// <returns>The block build from the <see cref="DxfDocument">document</see> content.</returns>
        /// <remarks>Only the entities contained in ModelSpace will make part of the block.</remarks>
        public static Block Create(DxfDocument doc, string name)
        {
            Block block = new Block(name);
            block.position = doc.DrawingVariables.InsBase;
            block.Record.Units = doc.DrawingVariables.InsUnits;
            List<DxfObject> entities = doc.Layouts.GetReferences(Layout.ModelSpaceName);
            foreach (DxfObject dxfObject in entities)
            {
                Object clone = ((EntityObject)dxfObject).Clone();

                AttributeDefinition attdef = clone as AttributeDefinition;
                if (attdef != null) block.AttributeDefinitions.Add(attdef);

                EntityObject entity = clone as EntityObject;
                if (entity != null) block.Entities.Add(entity);
            }

            return block;
        }
Beispiel #9
0
 internal TextStyles(DxfDocument document)
     : this(document, null)
 {
 }
Beispiel #10
0
 internal UCSs(DxfDocument document)
     : this(document, null)
 {
 }
Beispiel #11
0
 internal ShapeStyles(DxfDocument document, string handle)
     : base(document, DxfObjectCode.TextStyleTable, handle)
 {
 }
Beispiel #12
0
 internal UCSs(DxfDocument document, string handle = null)
     : this(document, 0, handle)
 {
 }
Beispiel #13
0
        /// <summary>
        /// Reads the whole stream.
        /// </summary>
        /// <param name="stream">Stream.</param>
        public DxfDocument Read(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException(nameof(stream));

            string dwgcodepage = CheckHeaderVariable(stream, HeaderVariableCode.DwgCodePage, out this.isBinary);

            try
            {
                if (this.isBinary)
                {
                    Encoding encoding;
                    DxfVersion version = DxfDocument.CheckDxfFileVersion(stream, out this.isBinary);
                    if (version >= DxfVersion.AutoCad2007)
                        encoding = Encoding.UTF8; // the strings in a dxf binary file seems to be stored as UTF8 even if the file looks like ANSI
                    else
                    {
                        if (string.IsNullOrEmpty(dwgcodepage))
                            encoding = Encoding.GetEncoding(Encoding.Default.WindowsCodePage); // use the default windows code page, if unable to read the code page header variable.
                        else
                        {
                            int codepage;
                            encoding = Encoding.GetEncoding(int.TryParse(dwgcodepage.Split('_')[1], out codepage) ? codepage : Encoding.Default.WindowsCodePage);
                        }
                    }
                    this.chunk = new BinaryCodeValueReader(new BinaryReader(stream), encoding);
                }
                else
                {
                    Encoding encoding;
                    Encoding encodingType = EncodingType.GetType(stream);
                    bool isUnicode = (encodingType.EncodingName == Encoding.UTF8.EncodingName) ||
                                     (encodingType.EncodingName == Encoding.BigEndianUnicode.EncodingName) ||
                                     (encodingType.EncodingName == Encoding.Unicode.EncodingName);

                    if (isUnicode)
                        encoding = Encoding.UTF8;
                    else
                    {
                        // if the file is not UTF-8 use the code page provided by the dxf file
                        if (string.IsNullOrEmpty(dwgcodepage))
                            encoding = Encoding.GetEncoding(Encoding.Default.WindowsCodePage); // use the default windows code page, if unable to read the code page header variable.
                        else
                        {
                            int codepage;
                            encoding = Encoding.GetEncoding(!int.TryParse(dwgcodepage.Split('_')[1], out codepage) ? Encoding.Default.WindowsCodePage : codepage);
                        }
                    }
                    this.chunk = new TextCodeValueReader(new StreamReader(stream, encoding, true));
                }
            }
            catch (Exception ex)
            {
                throw new IOException("Unknown error opening the reader.", ex);
            }

            this.doc = new DxfDocument(new HeaderVariables(), false);

            this.entityList = new Dictionary<EntityObject, string>();
            this.viewports = new Dictionary<Viewport, string>();
            this.hatchToPaths = new Dictionary<Hatch, List<HatchBoundaryPath>>();
            this.hatchContourns = new Dictionary<HatchBoundaryPath, List<string>>();
            this.decodedStrings = new Dictionary<string, string>();
            this.leaderAnnotation = new Dictionary<Leader, string>();

            // blocks
            this.nestedInserts = new Dictionary<Insert, string>();
            this.nestedDimensions = new Dictionary<Dimension, string>();
            this.blockRecords = new Dictionary<string, BlockRecord>(StringComparer.OrdinalIgnoreCase);
            this.blockEntities = new Dictionary<Block, List<EntityObject>>();

            // objects
            this.dictionaries = new Dictionary<string, DictionaryObject>(StringComparer.OrdinalIgnoreCase);
            this.groupEntities = new Dictionary<Group, List<string>>();
            this.dimStyleToHandles = new Dictionary<DimensionStyle, string[]>();
            this.imageDefReactors = new Dictionary<string, ImageDefinitionReactor>(StringComparer.OrdinalIgnoreCase);
            this.imgDefHandles = new Dictionary<string, ImageDefinition>(StringComparer.OrdinalIgnoreCase);
            this.imgToImgDefHandles = new Dictionary<Image, string>();
            this.mLineToStyleNames = new Dictionary<MLine, string>();
            this.underlayToDefinitionHandles = new Dictionary<Underlay, string>();
            this.underlayDefHandles = new Dictionary<string, UnderlayDefinition>();

            // for layouts errors workarounds
            this.blockRecordPointerToLayout = new Dictionary<string, BlockRecord>(StringComparer.OrdinalIgnoreCase);
            this.orphanLayouts = new List<Layout>();

            this.chunk.Next();

            // read the comments at the head of the file, any other comments will be ignored
            // they sometimes hold information about the program that has generated the dxf
            // binary files do not contain any comments
            this.doc.Comments.Clear();
            while (this.chunk.Code == 999)
            {
                this.doc.Comments.Add(this.chunk.ReadString());
                this.chunk.Next();
            }

            while (this.chunk.ReadString() != DxfObjectCode.EndOfFile)
            {
                if (this.chunk.ReadString() == DxfObjectCode.BeginSection)
                {
                    this.chunk.Next();
                    switch (this.chunk.ReadString())
                    {
                        case DxfObjectCode.HeaderSection:
                            this.ReadHeader();
                            break;
                        case DxfObjectCode.ClassesSection:
                            this.ReadClasses();
                            break;
                        case DxfObjectCode.TablesSection:
                            this.ReadTables();
                            break;
                        case DxfObjectCode.BlocksSection:
                            this.ReadBlocks();
                            break;
                        case DxfObjectCode.EntitiesSection:
                            this.ReadEntities();
                            break;
                        case DxfObjectCode.ObjectsSection:
                            this.ReadObjects();
                            break;
                        case DxfObjectCode.ThumbnailImageSection:
                            this.ReadThumbnailImage();
                            break;
                        case DxfObjectCode.AcdsDataSection:
                            this.ReadAcdsData();
                            break;
                        default:
                            throw new Exception(string.Format("Unknown section {0}.", this.chunk.ReadString()));
                    }
                }
                this.chunk.Next();
            }
            stream.Position = 0;

            // perform all necessary post processes
            this.PostProcesses();

            // to play safe we will add the default table objects to the document in case they do not exist,
            // if they already present nothing is overridden
            // add default layer
            this.doc.Layers.Add(Layer.Default);

            // add default line types
            this.doc.Linetypes.Add(Linetype.ByLayer);
            this.doc.Linetypes.Add(Linetype.ByBlock);
            this.doc.Linetypes.Add(Linetype.Continuous);

            // add default text style
            this.doc.TextStyles.Add(TextStyle.Default);

            // add default application registry
            this.doc.ApplicationRegistries.Add(ApplicationRegistry.Default);

            // add default dimension style
            this.doc.DimensionStyles.Add(DimensionStyle.Default);

            // add default MLine style
            this.doc.MlineStyles.Add(MLineStyle.Default);

            this.doc.ActiveLayout = Layout.ModelSpaceName;

            return this.doc;
        }
 internal ApplicationRegistries(DxfDocument document, string handle)
     : base(document, DxfObjectCode.ApplicationIdTable, handle)
 {
 }
Beispiel #15
0
 internal BlockRecords(DxfDocument document, string handle = null)
     : this(document, 0, handle)
 {
 }
 internal UnderlayDgnDefinitions(DxfDocument document, string handle)
     : base(document, DxfObjectCode.UnderlayDgnDefinitionDictionary, handle)
 {
     this.MaxCapacity = int.MaxValue;
 }
Beispiel #17
0
 internal ShapeStyles(DxfDocument document)
     : this(document, null)
 {
 }
Beispiel #18
0
        /// <summary>
        /// Creates a block from the content of a <see cref="DxfDocument">document</see>.
        /// </summary>
        /// <param name="doc">A <see cref="DxfDocument">DxfDocument</see> instance.</param>
        /// <param name="name">Name of the new block.</param>
        /// <returns>The block build from the <see cref="DxfDocument">document</see> content.</returns>
        /// <remarks>Only the entities contained in ModelSpace will make part of the block.</remarks>
        public static Block Create(DxfDocument doc, string name)
        {
            if (doc == null)
                throw new ArgumentNullException(nameof(doc));

            Block block = new Block(name) {Origin = doc.DrawingVariables.InsBase};
            block.Record.Units = doc.DrawingVariables.InsUnits;
            List<DxfObject> entities = doc.Layouts.GetReferences(Layout.ModelSpaceName);
            foreach (DxfObject dxfObject in entities)
            {
                EntityObject entity = dxfObject as EntityObject;
                if (entity == null)
                    continue;
                EntityObject clone = (EntityObject) entity.Clone();
                AttributeDefinition attdef = clone as AttributeDefinition;
                if (attdef != null)
                {
                    block.AttributeDefinitions.Add(attdef);
                    continue;
                }
                block.Entities.Add(clone);
            }
            return block;
        }
Beispiel #19
0
 internal ShapeStyles(DxfDocument document, string handle)
     : base(document, DxfObjectCode.TextStyleTable, handle)
 {
     this.MaxCapacity = short.MaxValue;
 }
Beispiel #20
0
 internal Groups(DxfDocument document, string handle)
     : base(document, DxfObjectCode.GroupDictionary, handle)
 {
     this.MaxCapacity = int.MaxValue;
 }
Beispiel #21
0
 internal Linetypes(DxfDocument document)
     : this(document, null)
 {
 }
Beispiel #22
0
        public void ImportDxfDrawing(string dxfName, ProjectLoadingView loadingForm)
        {

            loadingForm.ShowProgress(0,"导入环境初始化...");
            //DbConnection.GetConnection().Open();
            MainService mainService = ServiceFactory.GetMainService();
            TmpCaddService caddService = ServiceFactory.GetTmpCaddService();
            TmpCadxService cadxService = ServiceFactory.GetTmpCadxService();
            TmpCadmService cadmService = ServiceFactory.GetTmpCadmService();
            TmpCadzjService cadzjService = ServiceFactory.GetTmpCadzjService();
            TmpCadxdataService cadxdataService = ServiceFactory.GetTmpCadxdataService();
            
            int srid = mainService.GetGeometryColumnSRID("tmpcadd", "geometry");
            mainService.ClearCADTemps();
           
            
            DataSource ds = Ogr.Open(dxfName, 0);
            Driver drv = ds.GetDriver();
            loadingForm.ShowProgress(0, "导入图形数据...");
            for (int i = 0; i < ds.GetLayerCount(); i++)
            {
                Layer pLayer = ds.GetLayerByIndex(i);
                Feature feat = pLayer.GetNextFeature();
                while (feat != null)
                {
                    string handle = feat.GetFieldAsString(4);
                    string typeName = feat.GetFieldAsString(1).Trim().Replace("AcDbEntity:","");
                    string geomtryStr = "";
                    Geometry geometry = feat.GetGeometryRef();
                    geometry.FlattenTo2D();
                    geometry.ExportToWkt(out geomtryStr);
                    switch (typeName)
                    {
                        case "AcDbPolyline":
                        case "AcDbLine":
                            TmpCadx cadx = new TmpCadx(handle, geomtryStr, "POLYLINE", dxfName);
                            cadxService.Create(cadx);
                            break;
                        case "AcDbBlockReference":
                            //TmpCadd cadd=new TmpCadd(handle, geomtryStr, "POINT");
                            //caddService.Create(cadd);
                            //因为GDAL直接读取了块图形,因此,块在下面的方法和属性一起读取
                            break;
                        case "AcDbText:AcDbText":
                            TmpCadzj cadzj = new TmpCadzj(handle, geomtryStr, "TEXT", dxfName);
                            cadzjService.Create(cadzj);
                            break;
                      
                    }
                  
                    feat.Dispose();
                    feat = pLayer.GetNextFeature();
                }
            }
            

            //开始使用netDxf读取数据
            DxfDocument doc=DxfDocument.Load(dxfName);
            //开始读取点数据
            loadingForm.ShowProgress(40, "导入块参照属性...");
            for (int i = 0; i < doc.Inserts.Count; i++)
            {
                Insert insert= doc.Inserts[i];
                TmpCadd cadd=new TmpCadd();
                cadd.Handle = insert.Handle;
                cadd.EntityType = "POINT";
                cadd.FileName = dxfName;
                cadd.Geometry =
                    DbGeometry.FromText(string.Format("POINT({0} {1})", insert.Position.X, insert.Position.Y));
                caddService.Create(cadd);

                TmpCadxdata cadxdata = new TmpCadxdata();
                cadxdata.Handle = insert.Handle;
                cadxdata.Tc = insert.Layer.Name;
                cadxdata.Fh = insert.Block.Name;
                cadxdata.Fhdx = insert.Scale.X;
                cadxdata.Xzjd = insert.Rotation;
                cadxdata.FileName = dxfName;
                cadxdata = ReadXData(cadxdata, insert.XData);
                cadxdataService.Create(cadxdata);
            }

            //开始读取点数据
            loadingForm.ShowProgress(50, "导入文本数据...");
            for (int i = 0; i < doc.Texts.Count; i++)
            {
                Text insert = doc.Texts[i];
                //TmpCadd cadd = new TmpCadd();
                //cadd.Handle = insert.Handle;
                //cadd.EntityType = "POINT";
                //cadd.Geometry =
                //    DbGeometry.FromText(string.Format("POINT({0} {1})", insert.Position.X, insert.Position.Y));
                //caddService.Create(cadd);

                TmpCadxdata cadxdata = new TmpCadxdata();
                cadxdata.Handle = insert.Handle;
                cadxdata.Tc = insert.Layer.Name;
                cadxdata.Fh = insert.Style.FontFamilyName;
                cadxdata.Fhdx = insert.Height;
                cadxdata.Xzjd = insert.Rotation;
                cadxdata.Wbnr = insert.Value;
                cadxdata.FileName = dxfName;
                cadxdata = ReadXData(cadxdata, insert.XData);
                cadxdataService.Create(cadxdata);
            }

            //开始读取线数据
            loadingForm.ShowProgress(60, "导入线数据...");
            for (int i = 0; i < doc.Lines.Count; i++)
            {
                Line insert = doc.Lines[i];
                //TmpCadd cadd = new TmpCadd();
                //cadd.Handle = insert.Handle;
                //cadd.EntityType = "POINT";
                //cadd.Geometry =
                //    DbGeometry.FromText(string.Format("POINT({0} {1})", insert.Position.X, insert.Position.Y));
                //caddService.Create(cadd);

                TmpCadxdata cadxdata = new TmpCadxdata();
                cadxdata.Handle = insert.Handle;
                cadxdata.Tc = insert.Layer.Name;
                cadxdata.Fh = insert.Linetype.Name;
                cadxdata.Fhdx = insert.LinetypeScale;
                cadxdata.Xzjd = 0.0;
                cadxdata.Wbnr = "";
                cadxdata.FileName = dxfName;
                cadxdata = ReadXData(cadxdata, insert.XData);
                cadxdataService.Create(cadxdata);
            }
            loadingForm.ShowProgress(80, "导入多边形数据...");
            for (int i = 0; i < doc.LwPolylines.Count; i++)
            {
                LwPolyline insert = doc.LwPolylines[i];
                if (insert.IsClosed)
                {
                    //插入多边形
                    TmpCadx cadx = cadxService.GetTmpCadx(insert.Handle);
                    if (cadx != null)
                    {
                        TmpCadm cadm=new TmpCadm() {Handle = cadx.Handle,EntityType="POLYGON",FileName=dxfName};
                        string wkt = cadx.Geometry.AsText();
                        Geometry geometry = Ogr.ForceToPolygon(Geometry.CreateFromWkt(wkt));
                        string geomStr = "";
                        geometry.ExportToWkt(out geomStr);
                        geomStr = geomStr.Replace("LINESTRING", "POLYGON (") + ")";
                        cadm.Geometry = DbGeometry.FromText(geomStr);
                        cadmService.Create(cadm);
                    }
                }
                //TmpCadd cadd = new TmpCadd();
                //cadd.Handle = insert.Handle;
                //cadd.EntityType = "POINT";
                //cadd.Geometry =
                //    DbGeometry.FromText(string.Format("POINT({0} {1})", insert.Position.X, insert.Position.Y));
                //caddService.Create(cadd);

                TmpCadxdata cadxdata = new TmpCadxdata();
                cadxdata.Handle = insert.Handle;
                cadxdata.Tc = insert.Layer.Name;
                cadxdata.Fh = insert.Linetype.Name;
                cadxdata.Fhdx = insert.LinetypeScale;
                cadxdata.Xzjd = 0.0;
                cadxdata.Wbnr = "";
                cadxdata.FileName = dxfName;
                cadxdata = ReadXData(cadxdata, insert.XData);
                cadxdataService.Create(cadxdata);
            }

            for (int i = 0; i < doc.Polylines.Count; i++)
            {
                Polyline insert = doc.Polylines[i];
                if (insert.IsClosed)
                {
                    //插入多边形
                    TmpCadx cadx = cadxService.GetTmpCadx(insert.Handle);
                    if (cadx != null)
                    {
                        TmpCadm cadm = new TmpCadm() { Handle = cadx.Handle, EntityType = "POLYGON" ,FileName = dxfName};
                        string wkt = cadx.Geometry.AsText();
                        Geometry geometry = Ogr.ForceToPolygon(Geometry.CreateFromWkt(wkt));
                        string geomStr = "";
                        geometry.ExportToWkt(out geomStr);
                        geomStr=geomStr.Replace("LINESTRING", "POLYGON (")+")";
                        cadm.Geometry = DbGeometry.FromText(geomStr);
                        cadmService.Create(cadm);
                    }
                }
                //TmpCadd cadd = new TmpCadd();
                //cadd.Handle = insert.Handle;
                //cadd.EntityType = "POINT";
                //cadd.Geometry =
                //    DbGeometry.FromText(string.Format("POINT({0} {1})", insert.Position.X, insert.Position.Y));
                //caddService.Create(cadd);

                TmpCadxdata cadxdata = new TmpCadxdata();
                cadxdata.Handle = insert.Handle;
                cadxdata.Tc = insert.Layer.Name;
                cadxdata.Fh = insert.Linetype.Name;
                cadxdata.Fhdx = insert.LinetypeScale;
                cadxdata.Xzjd = 0.0;
                cadxdata.Wbnr = "";
                cadxdata.FileName = dxfName;
                cadxdata = ReadXData(cadxdata, insert.XData);
                cadxdataService.Create(cadxdata);
            }
            loadingForm.ShowProgress(100, "导入完成...");
            //mainService.Close();
        }
Beispiel #23
0
 internal UnderlayPdfDefinitions(DxfDocument document, string handle = null)
     : this(document, 0, handle)
 {
 }
Beispiel #24
0
 internal Layers(DxfDocument document, string handle)
     : base(document, DxfObjectCode.LayerTable, handle)
 {
     this.MaxCapacity = short.MaxValue;
 }
Beispiel #25
0
        private void DrawDxf(DxfDocument file)
        {
            _model.Name = file.Name;
            var minX = 10000000;
            var minY = 10000000;
            var maxX = 0;
            var maxY = 0;

            foreach (LwPolyline entity in _doc.LwPolylines)
            {
                if (!entity.IsClosed)
                {
                    continue;
                }
                int count = entity.Vertexes.Count;
                if (count == 10)
                {
                    double minNodeX = 10000000.0;
                    double minNodeY = 10000000.0;
                    double maxNodeX = 0.0;
                    double maxNodeY = 0.0;

                    foreach (LwPolylineVertex pt in entity.Vertexes)
                    {
                        if (pt.Position.X < minNodeX)
                        {
                            minNodeX = pt.Position.X;
                        }
                        if (pt.Position.Y < minNodeY)
                        {
                            minNodeY = pt.Position.Y;
                        }

                        if (pt.Position.X > maxNodeX)
                        {
                            maxNodeX = pt.Position.X;
                        }
                        if (pt.Position.Y > maxNodeY)
                        {
                            maxNodeY = pt.Position.Y;
                        }
                    }

                    double dist = maxNodeX - minNodeX;
                    if (0.4 > dist || dist > 0.7)
                    {
                        continue;
                    }

                    double centerX = (maxNodeX + minNodeX) / 2.0;
                    double centerY = (maxNodeY + minNodeY) / 2.0;

                    int t = count;

                    var newX = (int)(centerX * 2.0);
                    var newY = (int)(centerY * 2.0);

                    if (newX < minX)
                    {
                        minX = newX - 1;
                    }
                    if (newY < minY)
                    {
                        minY = newY - 1;
                    }

                    if (newX > maxX)
                    {
                        maxX = newX + 1;
                    }
                    if (newY > maxY)
                    {
                        maxY = newY + 1;
                    }

                    var newNode = new Node
                    {
                        GridX = newX,
                        GridY = newY
                    };
                    _model.AddNode(newNode);
                }
            }

            foreach (var entity in _doc.Arcs)
            {
            }

            foreach (var entity in _doc.Circles)
            {
                //pixel hole are about 0.5 inches or 0.25
                if (0.2 > entity.Radius || entity.Radius > 0.3)
                {
                    continue;
                }

                var newX = (int)(entity.Center.X * 2.0);
                var newY = (int)(entity.Center.Y * 2.0);

                if (newX < minX)
                {
                    minX = newX - 1;
                }
                if (newY < minY)
                {
                    minY = newY - 1;
                }

                if (newX > maxX)
                {
                    maxX = newX + 1;
                }
                if (newY > maxY)
                {
                    maxY = newY + 1;
                }

                var newNode = new Node
                {
                    GridX = newX,
                    GridY = newY
                };
                _model.AddNode(newNode);
            }

            var width  = maxX - minX;
            var heigth = maxY - minY;

            _model.SizeX = width;
            _model.SizeY = heigth;

            foreach (var node in _model.GetNodes())
            {
                //var scaleX = _model.SizeX / 2 + node.GridX;
                //var scaleY = _model.SizeY / 2 + node.GridY;
                var scaleX = node.GridX - minX;
                var scaleY = node.GridY - minY;
                Debug.WriteLine(scaleX);
                Debug.WriteLine(scaleY);
                node.GridX = scaleX;
                node.GridY = scaleY;
            }

            listDataGridView.DataSource = _model.GetBinding();
            DrawGrid();
        }
Beispiel #26
0
 internal ApplicationRegistries(DxfDocument document, string handle)
     : base(document, DxfObjectCode.ApplicationIdTable, handle)
 {
     this.MaxCapacity = short.MaxValue;
 }
Beispiel #27
0
 internal Views(DxfDocument document)
     : this(document, null)
 {
 }
Beispiel #28
0
 internal Layouts(DxfDocument document, string handle)
     : base(document, DxfObjectCode.LayoutDictionary, handle)
 {
     this.MaxCapacity = short.MaxValue;
     this.references  = null;
 }
Beispiel #29
0
 internal Views(DxfDocument document, string handle)
     : base(document, DxfObjectCode.ViewTable, handle)
 {
 }
 internal ApplicationRegistries(DxfDocument document)
     : this(document, null)
 {
 }
Beispiel #31
0
        /// <summary>
        /// 保存为DXF格式
        /// </summary>
        /// <param name="figures"></param>
        /// <param name="path"></param>
        public static void WriteDXF(List <FigureBaseModel> figures, string path)
        {
            DxfDocument dxf = new DxfDocument();

            foreach (FigureBaseModel figure in figures)
            {
                switch (figure.Type)
                {
                case FigureTypes.Arc:
                {
                    var    fg         = figure as ArcModel;
                    double startAngle = double.IsNaN(fg.StartAngle) ? 0 : fg.StartAngle;
                    double endAngle   = double.IsNaN(fg.EndAngle) ? 0 : fg.EndAngle;
                    double sweepAngle = double.IsNaN(fg.AngleSweep) ? 0 : fg.AngleSweep;
                    if (fg.IsClockwise)
                    {
                        endAngle = startAngle - sweepAngle;
                    }
                    else
                    {
                        endAngle = startAngle + sweepAngle;
                    }
                    if (endAngle > 360)
                    {
                        endAngle = endAngle - 360;
                    }
                    if (sweepAngle < 0)
                    {
                        double temp = startAngle;
                        startAngle = endAngle;
                        endAngle   = temp;
                    }

                    Arc arc = new Arc(new Vector3(fg.Center.X, fg.Center.Y, 0),
                                      fg.Radius,
                                      startAngle,
                                      endAngle
                                      );
                    arc.Layer             = new Layer("arc");
                    arc.Layer.Color.Index = (short)(figure.LayerId);
                    arc.Layer.Name        = (figure.LayerId).ToString();
                    dxf.AddEntity(arc);
                }
                break;

                case FigureTypes.Circle:
                {
                    var    fg     = figure as CircleModel;
                    Circle circle = new Circle(new Vector3(fg.Center.X, fg.Center.Y, 0), fg.Radius);
                    circle.Layer             = new Layer("circle with spaces");
                    circle.Layer.Color.Index = (short)(figure.LayerId);
                    circle.Layer.Name        = (figure.LayerId).ToString();
                    dxf.AddEntity(circle);
                }
                break;

                case FigureTypes.Point:
                {
                    var   fg     = figure as PointModel;
                    Point point1 = new Point(new Vector3(fg.Point.X, fg.Point.Y, 0));
                    point1.Layer             = new Layer("point");
                    point1.Layer.Color.Index = (short)(figure.LayerId);
                    point1.Layer.Name        = (figure.LayerId).ToString();
                    dxf.AddEntity(point1);
                }
                break;

                case FigureTypes.LwPolyline:
                {
                    var fg = figure as LwPolylineModel;
                    List <LwPolylineVertex> lwVertexes = new List <LwPolylineVertex>();
                    foreach (UnitPointBulge pt in fg.Points)
                    {
                        LwPolylineVertex lwVertex = new LwPolylineVertex(pt.Point.X, pt.Point.Y, double.IsNaN(pt.Bulge) ? 0 : pt.Bulge);
                        lwVertexes.Add(lwVertex);
                    }
                    LwPolyline lwPolyline = new LwPolyline(lwVertexes, true);
                    lwPolyline.IsClosed          = fg.IsFill;
                    lwPolyline.Layer.Color.Index = (short)(figure.LayerId);
                    lwPolyline.Layer             = new Layer("lwpolyline");
                    lwPolyline.Layer.Name        = (figure.LayerId).ToString();
                    dxf.AddEntity(lwPolyline);
                }
                break;

                case FigureTypes.PolyBezier:
                {
                }
                break;

                default:
                    break;
                }
            }
            dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2010;
            dxf.Save(path);
        }
Beispiel #32
0
 internal LineTypes(DxfDocument document, string handle = null)
     : this(document, 0, handle)
 {
 }
Beispiel #33
0
 internal ImageDefinitions(DxfDocument document)
     : this(document, null)
 {
 }
Beispiel #34
0
 internal UnderlayDgnDefinitions(DxfDocument document)
     : this(document, null)
 {
 }
Beispiel #35
0
 internal ImageDefinitions(DxfDocument document, string handle)
     : base(document, DxfObjectCode.ImageDefDictionary, handle)
 {
     MaxCapacity = int.MaxValue;
 }
Beispiel #36
0
        /// <summary>
        /// Saves a block to a dxf file.
        /// </summary>
        /// <param name="file">Dxf file name.</param>
        /// <param name="version">Version of the dxf database version.</param>
        /// <param name="isBinary">Defines if the file will be saved as binary, by default it will be saved as text</param>
        /// <returns>Return true if the file has been successfully save, false otherwise.</returns>
        public bool Save(string file, DxfVersion version, bool isBinary = false)
        {
            DxfDocument dwg = new DxfDocument(version);
            dwg.DrawingVariables.InsBase = this.position;
            dwg.DrawingVariables.InsUnits = this.Record.Units;

            Block copy = (Block) this.Clone();
            dwg.AddEntity(copy.Entities);

            foreach (AttributeDefinition attdef in copy.AttributeDefinitions.Values)
            {
                dwg.AddEntity(attdef);
            }

            return dwg.Save(file, isBinary);
        }
Beispiel #37
0
        /// <summary>
        /// Reads the whole stream.
        /// </summary>
        /// <param name="stream">Stream.</param>
        public DxfDocument Read(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException("stream", "The stream cannot be null");

            string dwgcodepage = CheckHeaderVariable(stream, HeaderVariableCode.DwgCodePage, out this.isBinary);

            try
            {
                if (this.isBinary)
                {
                    Encoding encoding;
                    DxfVersion version = DxfDocument.CheckDxfFileVersion(stream, out this.isBinary);
                    if (version >= DxfVersion.AutoCad2007)
                        encoding = Encoding.UTF8; // the strings in a dxf binary file seems to be stored as UTF8 even if the file looks like ANSI
                    else
                    {
                        if (string.IsNullOrEmpty(dwgcodepage))
                            encoding = Encoding.GetEncoding(Encoding.Default.WindowsCodePage); // use the default windows code page, if unable to read the code page header variable.
                        else
                        {
                            int codepage;
                            if (!int.TryParse(dwgcodepage.Split('_')[1], out codepage))
                                encoding = Encoding.GetEncoding(Encoding.Default.WindowsCodePage); // use the default windows code page, if unable to read the code page header variable.
                            else
                                encoding = Encoding.GetEncoding(codepage);
                        }
                    }
                    this.chunk = new BinaryCodeValueReader(new BinaryReader(stream), encoding);
                }
                else
                {
                    Encoding encoding;
                    Encoding encodingType = EncodingType.GetType(stream);
                    bool isUnicode = (encodingType.EncodingName == Encoding.UTF8.EncodingName) ||
                                     (encodingType.EncodingName == Encoding.BigEndianUnicode.EncodingName) ||
                                     (encodingType.EncodingName == Encoding.Unicode.EncodingName);

                    if (isUnicode)
                        encoding = Encoding.UTF8;
                    else
                    {
                        // if the file is not UTF-8 use the code page provided by the dxf file
                        if (string.IsNullOrEmpty(dwgcodepage))
                            encoding = Encoding.GetEncoding(Encoding.Default.WindowsCodePage); // use the default windows code page, if unable to read the code page header variable.
                        else
                        {
                            int codepage;
                            if (!int.TryParse(dwgcodepage.Split('_')[1], out codepage))
                                encoding = Encoding.GetEncoding(Encoding.Default.WindowsCodePage); // use the default windows code page, if unable to read the code page header variable.
                            else
                                encoding = Encoding.GetEncoding(codepage); // use the default windows code page, if unable to read the code page header variable.
                        }
                    }
                    this.chunk = new TextCodeValueReader(new StreamReader(stream, encoding, true));
                }
            }
            catch (Exception ex)
            {
                throw (new DxfException("Unknown error opening the reader.", ex));
            }

            this.doc = new DxfDocument(new HeaderVariables(), false);

            this.entityList = new Dictionary<EntityObject, string>();
            this.viewports = new Dictionary<Viewport, string>();
            this.hatchToPaths = new Dictionary<Hatch, List<HatchBoundaryPath>>();
            this.hatchContourns = new Dictionary<HatchBoundaryPath, List<string>>();
            this.decodedStrings = new Dictionary<string, string>();

            // blocks
            this.nestedInserts = new Dictionary<Insert, string>();
            this.nestedDimensions = new Dictionary<Dimension, string>();
            this.blockRecords = new Dictionary<string, BlockRecord>(StringComparer.OrdinalIgnoreCase);
            this.blockEntities = new Dictionary<Block, List<EntityObject>>();

            // objects
            this.dictionaries = new Dictionary<string, DictionaryObject>(StringComparer.OrdinalIgnoreCase);
            this.groupEntities = new Dictionary<Group, List<string>>();
            this.dimStyleToHandles = new Dictionary<DimensionStyle, string[]>();
            this.imageDefReactors = new Dictionary<string, ImageDefReactor>(StringComparer.OrdinalIgnoreCase);
            this.imgDefHandles = new Dictionary<string, ImageDef>(StringComparer.OrdinalIgnoreCase);
            this.imgToImgDefHandles = new Dictionary<Image, string>();
            this.mLineToStyleNames = new Dictionary<MLine, string>();

            // for layouts errors workarounds
            this.blockRecordPointerToLayout = new Dictionary<string, BlockRecord>(StringComparer.OrdinalIgnoreCase);
            this.orphanLayouts = new List<Layout>();

            this.chunk.Next();

            // read the comments at the head of the file, any other comments will be ignored
            // they sometimes hold information about the program that has generated the dxf
            // binary files do not contain any comments
            this.doc.Comments.Clear();
            while (this.chunk.Code == 999)
            {
                this.doc.Comments.Add(this.chunk.ReadString());
                this.chunk.Next();
            }

            while (this.chunk.ReadString() != DxfObjectCode.EndOfFile)
            {
                if (this.chunk.ReadString() == DxfObjectCode.BeginSection)
                {
                    this.chunk.Next();
                    switch (this.chunk.ReadString())
                    {
                        case DxfObjectCode.HeaderSection:
                            this.ReadHeader();
                            break;
                        case DxfObjectCode.ClassesSection:
                            this.ReadClasses();
                            break;
                        case DxfObjectCode.TablesSection:
                            this.ReadTables();
                            break;
                        case DxfObjectCode.BlocksSection:
                            this.ReadBlocks();
                            break;
                        case DxfObjectCode.EntitiesSection:
                            this.ReadEntities();
                            break;
                        case DxfObjectCode.ObjectsSection:
                            this.ReadObjects();
                            break;
                        case DxfObjectCode.ThumbnailImageSection:
                            this.ReadThumbnailImage();
                            break;
                        case DxfObjectCode.AcdsDataSection:
                            this.ReadAcdsData();
                            break;
                        default:
                            throw new InvalidDxfSectionException(this.chunk.ReadString(), string.Format("Unknown section {0}.", this.chunk.ReadString()));
                    }
                }
                this.chunk.Next();
            }
            stream.Position = 0;

            // post process the dimension style list to assign the variables DIMTXSTY, DIMBLK, DIMBLK1, DIMBLK2, DIMLTYPE, DILTEX1, and DIMLTEX2
            foreach (KeyValuePair<DimensionStyle, string[]> pair in this.dimStyleToHandles)
            {
                DimensionStyle defaultDim = DimensionStyle.Default;

                BlockRecord record;

                record = this.doc.GetObjectByHandle(pair.Value[0]) as BlockRecord;
                pair.Key.DIMBLK = record == null ? null : this.doc.Blocks[record.Name];

                record = this.doc.GetObjectByHandle(pair.Value[1]) as BlockRecord;
                pair.Key.DIMBLK1 = record == null ? null : this.doc.Blocks[record.Name];

                record = this.doc.GetObjectByHandle(pair.Value[2]) as BlockRecord;
                pair.Key.DIMBLK2 = record == null ? null : this.doc.Blocks[record.Name];

                TextStyle txtStyle;

                txtStyle = this.doc.GetObjectByHandle(pair.Value[3]) as TextStyle;
                pair.Key.DIMTXSTY = txtStyle == null ? this.doc.TextStyles[defaultDim.DIMTXSTY.Name] : this.doc.TextStyles[txtStyle.Name];

                LineType ltype;

                ltype = this.doc.GetObjectByHandle(pair.Value[4]) as LineType;
                pair.Key.DIMLTYPE = ltype == null ? this.doc.LineTypes[defaultDim.DIMLTYPE.Name] : this.doc.LineTypes[ltype.Name];

                ltype = this.doc.GetObjectByHandle(pair.Value[5]) as LineType;
                pair.Key.DIMLTEX1 = ltype == null ? this.doc.LineTypes[defaultDim.DIMLTEX1.Name] : this.doc.LineTypes[ltype.Name];

                ltype = this.doc.GetObjectByHandle(pair.Value[6]) as LineType;
                pair.Key.DIMLTEX2 = ltype == null ? this.doc.LineTypes[defaultDim.DIMLTEX2.Name] : this.doc.LineTypes[ltype.Name];
            }

            // post process the image list to assign their image definitions.
            foreach (KeyValuePair<Image, string> pair in this.imgToImgDefHandles)
            {
                Image image = pair.Key;
                image.Definition = this.imgDefHandles[pair.Value];
                image.Definition.Reactors.Add(image.Handle, this.imageDefReactors[image.Handle]);

                // we still need to set the definitive image size, now that we know all units involved
                double factor = UnitHelper.ConversionFactor(this.doc.DrawingVariables.InsUnits, this.doc.RasterVariables.Units);
                image.Width *= factor;
                image.Height *= factor;
            }

            // post process the MLines to assign their MLineStyle
            foreach (KeyValuePair<MLine, string> pair in this.mLineToStyleNames)
            {
                MLine mline = pair.Key;
                mline.Style = this.GetMLineStyle(pair.Value);
            }

            // post process the entities of the blocks
            foreach (KeyValuePair<Block, List<EntityObject>> pair in this.blockEntities)
            {
                Block block = pair.Key;
                foreach (EntityObject entity in pair.Value)
                {
                    // now that we have all information required by the block entities we can add them to the document
                    // entities like MLine and Image require information that is defined AFTER the block section,
                    // this is the case of the MLineStyle and ImageDef that are described in the objects section
                    block.Entities.Add(entity);
                }
            }

            // add the dxf entities to the document
            foreach (KeyValuePair<EntityObject, string> pair in this.entityList)
            {
                Layout layout;
                Block block;
                if (pair.Value == null)
                {
                    // the Model layout is the default in case the entity has not one defined
                    layout = this.doc.Layouts[Layout.ModelSpaceName];
                    block = layout.AssociatedBlock;
                }
                else
                {
                    block = this.GetBlock(((BlockRecord) this.doc.GetObjectByHandle(pair.Value)).Name);
                    layout = block.Record.Layout;
                }

                // the viewport with id 1 is stored directly in the layout since it has no graphical representation
                Viewport viewport = pair.Key as Viewport;
                if (viewport != null)
                {
                    if (viewport.Id == 1)
                    {
                        // the base layout viewport has always id = 1 and we will not add it to the entities list of the document.
                        // this viewport has no graphical representation, it is the view of the paper space layout itself and it does not show the model.
                        layout.Viewport = viewport;
                        layout.Viewport.Owner = block;
                    }
                    else
                    {
                        this.doc.ActiveLayout = layout.Name;
                        this.doc.AddEntity(pair.Key, false, false);
                    }
                }
                else
                {
                    // apply the units scale to the insertion scale (this is for not nested blocks)
                    Insert insert = pair.Key as Insert;
                    if (insert != null)
                    {
                        double scale = UnitHelper.ConversionFactor(this.doc.DrawingVariables.InsUnits, insert.Block.Record.Units);
                        insert.Scale *= scale;
                    }
                    this.doc.ActiveLayout = layout.Name;
                    this.doc.AddEntity(pair.Key, false, false);
                }
            }

            // assign a handle to the default layout viewports
            foreach (Layout layout in this.doc.Layouts)
            {
                if (layout.Viewport == null) continue;

                if (string.IsNullOrEmpty(layout.Viewport.Handle))
                    this.doc.NumHandles = layout.Viewport.AsignHandle(this.doc.NumHandles);
            }

            // post process viewports clipping boundaries
            foreach (KeyValuePair<Viewport, string> pair in this.viewports)
            {
                EntityObject entity = this.doc.GetObjectByHandle(pair.Value) as EntityObject;
                if (entity != null )
                    pair.Key.ClippingBoundary = entity;
            }

            // post process the hatch boundary paths
            foreach (KeyValuePair<Hatch, List<HatchBoundaryPath>> pair in this.hatchToPaths)
            {
                Hatch hatch = pair.Key;
                foreach (HatchBoundaryPath path in pair.Value)
                {
                    List<string> entities = this.hatchContourns[path];
                    foreach (string handle in entities)
                    {
                        EntityObject entity = this.doc.GetObjectByHandle(handle) as EntityObject;
                        if (entity != null)
                            path.AddContour(entity);
                    }
                    hatch.BoundaryPaths.Add(path);
                }
            }

            // post process group entities
            foreach (KeyValuePair<Group, List<string>> pair in this.groupEntities)
            {
                foreach (string handle in pair.Value)
                {
                    EntityObject entity = this.doc.GetObjectByHandle(handle) as EntityObject;
                    if (entity != null)
                        pair.Key.Entities.Add(entity);
                }
            }

            // to play safe we will add the default table objects to the document in case they do not exist,
            // if they already present nothing is overridden
            // add default layer
            this.doc.Layers.Add(Layer.Default);

            // add default line types
            this.doc.LineTypes.Add(LineType.ByLayer);
            this.doc.LineTypes.Add(LineType.ByBlock);
            this.doc.LineTypes.Add(LineType.Continuous);

            // add default text style
            this.doc.TextStyles.Add(TextStyle.Default);

            // add default application registry
            this.doc.ApplicationRegistries.Add(ApplicationRegistry.Default);

            // add default dimension style
            this.doc.DimensionStyles.Add(DimensionStyle.Default);

            // add default MLine style
            this.doc.MlineStyles.Add(MLineStyle.Default);

            this.doc.ActiveLayout = Layout.ModelSpaceName;

            return this.doc;
        }