domcr / acadsharp Goto Github PK
View Code? Open in Web Editor NEWC# library to read/write cad files like dxf/dwg.
License: MIT License
C# library to read/write cad files like dxf/dwg.
License: MIT License
The Dimension.Text
property should return an empty or explicit text when the value is not null.
It should return a default text, i. e. the formatted Measurement, when the value is null.
The implementation handles null and empty in the same way.
////// Dimension text explicitly entered by the user /// /// /// Optional; default is the measurement. /// If null, the dimension measurement is drawn as the text, /// if ““ (one blank space), the text is suppressed.Anything else is drawn as the text /// [DxfCodeValue(DxfReferenceType.Optional, 1)] public string Text { get { return string.IsNullOrEmpty(_text) ? this.Measurement.ToString() : this._text; } set { this._text = value; } }
I would propose to format the Measurement
value after rounding to Dimension.Style.DecimalPlaces
and using the Dimension.Style.DecimalSeparator
. Perhaps it even makes sense to add unit string etc.
Describe the bug
In the attached DWG file the program finds only one geometric entity instead of the around 200 expected entities.
To Reproduce
Use the DwgReader.Read() function to read the attached DWG file obtaining the corresponding CadDocument object.
Expected behavior
The CadDocument object obtained from the attached DWG file should contain around 200 entities, not only one.
CadTemplate should be able to bypass the readMapped method so it can avoid the mapper and assign a property to an object.
Once this refactor is done the changes in this PR have to be modified using this new method instead the Build
#83
Many entites have a list of Reactors, represented by a Dictionary handle-->object.
The Dictionary only contains the keys but not the resolved values = object references.
Expected:
In The CadTemplate.Build method line 55 ff. the list of ReactorsHandles shall be used to fill the dictionaries with references resolved by the object handles. However the list of ReactorsHandles is empty.
The list of ReactorsHandles should be filled in method DwgObjectSectionReader.readReactorsAndDictionaryHandle. But instead of adding the handles to the ReactorsHandles list the handles are directly added into Reactors dictionary.
Code in DwgObjectSectionReader.readReactorsAndDictionaryHandle should be changed as follows:
for (int i = 0; i < numberOfReactors; ++i) //[Reactors (soft pointer)] //template.CadObject.Reactors.Add(this.handleReference(), null); template.ReactorsHandles.Add(this.handleReference());
Describe the bug
I'm unsure as to why any DxF file I create using SysCAD causes an exception to be thrown when trying to open it in this library.
To Reproduce
Try to read the DxfFile I've attached.
Expected behavior
An exception should not be thrown as I'm still able to open this file in other .NET DxfFile parsers.
Additional context
05_Flowsheet.zip
Hi, I tried to read a dxf
file by this package and distinguish every entity from its layer name, but unfortunately all Layer.Name
in Entities
had the same value: "0"
- the default layer name.
I also tried to use GetCadObject
by their handler
but cadObject
s had the same result, too.
Thanks for your attention. I’m looking forward to your reply.
@DomCR I can't run this c# example project. It directly reports an error. No dependencies were found for the project. You mean that it can read all the information of DWG, can it be displayed? It seems to me that the code can only read information instead of displaying graphics. I want to import the DWG file and display the drawing in the window.
Originally posted by @socketing in #35 (comment)
Arc
, Insert
and TextEntity
have a rotation that is calculated in the set in case that the AlignmentPoint
or the Rotation
changes.
We need an investigation to make sure that this only affects the 2D, X and Y, of the coordinates and does not use the Normal to calculate the relative plane.
If that's the case, the methods will need to change to calculate the angle in 3D using the Normal.
Hello ACadSharp Team,
I’m currently experiencing an issue while trying to read a file in C# using your library. The error message I receive is as follows:
System.ArgumentOutOfRangeException: TimeSpan overflowed because the duration is too long.
at ACadSharp.IO.DWG.DwgStreamReaderBase.ReadTimeSpan()
at ACadSharp.IO.DWG.DwgHeaderReader.Read(Int32 acadMaintenanceVersion, DwgHeaderHandlesCollection& objectPointers)
at ACadSharp.IO.DwgReader.ReadHeader()
at ACadSharp.IO.DwgReader.Read()
at ACadSharp.IO.DwgReader.Read(String filename, DwgReaderConfiguration configuration, NotificationEventHandler notification)
The file looks like this:
I kindly request your assistance in resolving this issue.
Thank you.
Describe the bug
I tried to open a DXF files created in LibreCAD and got a CadLib.Exceptions.DxfException
To Reproduce
Download LibreCAD from https://librecad.org
Create any DXF file, and save it on disk. Open with ACadSharp library.
Expected behavior
File must be opened without exceptions.
Additional context
Circle.zip
Describe the bug
I'm trying to convert a DWG 2010 to DXF. But the file saved is corrupted.
To Reproduce
var doc = new DwgReader("test.dwg").Read();
var writer = new DxfWriter($"test.dxf", doc, false);
writer.Write();
Additional context
test.zip
In the opendesign specification, 3B is a sequence of 1 to 3 bits. Keep reading bits until a zero bit is encountered or until the 3rd bit is read, whatever comes first.
The implementation of the read3bits function in libredwg project is blow.
/** Read 1-3 bits
* Keep reading bits until a zero bit is encountered, => 0,2,6,7.
* 0: 0, 10: 2, 110: 6, 111: 7. 100 for 4 or 101 for 5 is invalid.
*/
BITCODE_3B
bit_read_3B (Bit_Chain *dat)
{
BITCODE_3B result = bit_read_B (dat);
if (result)
{
BITCODE_3B next = bit_read_B (dat);
if (next)
{
next = bit_read_B (dat);
return next ? 7 : 6;
}
else
{
return 2;
}
}
else
{
return 0;
}
}
Describe the bug
This DWG should have 200+ objects. Only returns a single point from ACadSharp
Expected behavior
Read should return Points and Text labels, and a polyline or 2
Screenshots
This is how it looks in True View
Additional context
I ran it thru ConvertCloud.com and it loads correctly in ACadSharp. QueenCity DXF is another Point/Text/Lines drawing with similar results.
In the DxfSubclassMarker class https://github.com/DomCR/ACadSharp/blob/master/ACadSharp/DxfSubclassMarker.cs, then PolylineVertex constant has a whitespace at the end. This prevents it from ever matching the string in the file.
Hi @DomCR, very interesting project. I'm C# developer and I'd like to collaborate. How can I do it?
Describe the bug
Cannot read with AcadSharp a dwg file written with AcadSharp.
To Reproduce
I've created a dwg file with AcadSharp and then saved.
All the documents section (such as the Header) are as default.
When I try to load the file with DwgReader
it throws the following exception:
ACadSharp.Exceptions.DwgNotSupportedException: 'Dwg version not recognised
.
Write dwg code:
// new document
ACadSharp.CadDocument doc = new ACadSharp.CadDocument();
// write file
ACadSharp.IO.DwgWriter writer = new ACadSharp.IO.DwgWriter("Test.dwg", doc);
writer.Write();
Read dwg code:
ACadSharp.CadDocument loaded = ACadSharp.IO.DwgReader.Read("Test.dwg");
Full exception and stack trace:
ACadSharp.Exceptions.DwgNotSupportedException: 'Dwg version not recognised
at ACadSharp.IO.DWG.DwgFileHeader.CreateFileHeader(ACadVersion version) in C:\Users\stage1\source\repos\ACadSharp\ACadSharp\IO\DWG\FileHeaders\DwgFileHeader.cs:line 37
at ACadSharp.IO.DwgReader.readFileHeader() in C:\Users\stage1\source\repos\ACadSharp\ACadSharp\IO\DWG\DwgReader.cs:line 225
at ACadSharp.IO.DwgReader.Read() in C:\Users\stage1\source\repos\ACadSharp\ACadSharp\IO\DWG\DwgReader.cs:line 97
at ACadSharp.IO.DwgReader.Read(String filename, DwgReaderConfiguration configuration, NotificationEventHandler notification) in C:\Users\stage1\source\repos\ACadSharp\ACadSharp\IO\DWG\DwgReader.cs:line 83
at ACadSharp.IO.DwgReader.Read(String filename, NotificationEventHandler notification) in C:\Users\stage1\source\repos\ACadSharp\ACadSharp\IO\DWG\DwgReader.cs:line 66
Expected behavior
No exception
AMASYAELK_2000.zip
Hi, I get this type of error when to open the DWG file attached. Great project, keep it up please. Thanks.
System.ArgumentException: 'The item with the same key has already been added.'
Using ver 1.4.1.0
Describe the bug
I'm attempting to round trip a load/save in ACADSharp. From DWG2018 to DXF2013. Arcs are missing or flipped. Lost entity color.
Is there more I need to set up before saving dxf?
To Reproduce
// See attached K6-2018.zip file
string filenameDwg2018 = "C:\K6-2018.dwg";
string filenameDxf2013 = "C:\K6-2013.dxf";
CadDocument doc = ACadSharp.IO.DwgReader.Read(filenameDwg2018);
doc.Header.Version = ACadVersion.AC1027;
using (DxfWriter writer = new DxfWriter(filenameDxf2013, doc, false))
{
writer.Write();
}
Expected behavior
I would like the DWG entities to save to DXF correctly.
If applicable, add screenshots to help explain your problem.
Additional context
Add any other context about the problem here.
If the issue is related to an specific dwg/dxf file and if able, attach that file to the issue of an equivalent with the same error.
K6-2018.zip
Reading a dwg that is roughly 1400kb took 25 seconds to complete. I tracked down where the bottleneck was occurring and it happens in the DwgObjectSecionReader.cs. It seams that in every read loop, the stream gets copied at least 3 times in the getEntityType method. I changed this by creating a buffer in the initializer for the class and then creating a new memory stream from that buffer (that way the buffer only gets copied once when the class initializes). This reduced the read time to 500 ms. Just fyi. Great project.
Describe the bug
All the insert Attributtes are returning null in Tag Property.
To Reproduce
Created a block with name 'M8_COM' with tags =
'TRA_PEZ',
'DES_PEZ',
'NOT_PEZ',
'TIP_PEZ',
'ING_PEZ',
'COS_PEZ'
Insert the block and fill the properties.
Save the DWG as AutoCad 2010.
Tryed to read the block:
using (DwgReader reader = new DwgReader(file))
{
CadDocument acCurdb = reader.Read();
List<Insert> inserts = acCurdb.Entities.ToList().FindAll(x => x is ACadSharp.Entities.Insert).Select(x => x as ACadSharp.Entities.Insert).ToList();
forearch(var insert in inserts)
{
var atts = bloco.Attributes.ToList();
}
}
Expected behavior
When reading Tag property, return 'TRA_PEZ', 'DES_PEZ'...
Additional context
Obs.: I need the DWGs in 2010, for compatibility with others softwares.
In the example of [ACadSharp. Tests], it seems that there is only an example of creating a block. I am not sure how to create a block reference using this block.
I think I need to use the [insert] class, but it doesn't work. Can you add a sample code for block references?
Thank you very very much
Hi Albert,
I'm running into a pretty big issue regarding load time. I have a 74K object count DWG that takes over 300 seconds to load in AS. Lots of small lines in this drawing. I could send you the DWG if interested.
Also, is there a timeline for when Polyline save will be implemented?
Thank you,
Matt
Describe the bug
Loading the attached DXF has a lot of errors and get pretty bad results. If I run it thru Cloud Convert and reload it, it looks great.
To Reproduce
Unzip and load ALFA Sportwagon-4 views.dxf - I get lots of circular arcs
Convert it in (https://cloudconvert.com/) and it looks great
Expected behavior
Should get 4 nice views of the wagon
Additional context
With most of my dxf/dwg files, I have no idea where they came from.
ALFA Sportwagon-4 views.zip
ALFA Sportwagon-4 views-CloudConvert.zip
Thank you so much for your code, it did write pretty well.
I am curious about, where can I find geometry data when I read a CAD file.
Right now I just got CadDocument doc, but I can not find the geometry data. Is it anything I did wrong?
In https://github.com/DomCR/ACadSharp/blob/master/ACadSharp/Classes/DxfClassCollection.cs, the list 'Dictionary' will throw an exception if an item is added twice (which in my case, the dxf for some reason has two items the same). Not sure what to do here, my easy fix was to change line 19 to this: _list[item.DxfName]= item;
which just replaces any duplicate classes.
Originally posted by @gktval in #63 (comment)
Is your feature request related to a problem? Please describe.
I want to read the objects contained in the layouts tabs
Describe the solution you'd like
The list of Entities (ACadSharp.CadObjectCollection<ACadSharp.Entities.Entity>) returning items from Layout
In https://github.com/DomCR/ACadSharp/blob/master/ACadSharp/Entities/ViewPort.cs, FrozenLayers method is never initialized and will throw a NullReferenceException in the CadViewportTemplate. (so just add FrozenLayers = new List<Layer>();
to the constructor.
Originally posted by @gktval in #63 (comment)
I can't run this instance project, ACadSharp class library in the various errors, is my use of the method wrong?
System.Exception: Exception of type 'System.Exception'
the file:
FULL.zip
Hi @DomCR
Many thanks about this project, i have a problem when try get a location of cad block, how we can do that ?
Is this a development project in progress with it?
Hi Dom,
When I read this DWG the BoundaryPath Edges and Entites are empty. I can't find any vector information in the hatch entity. It loads in True View and another cad package. Could you take a quick look and tell me if the data is there or not?
Thank you
In the DxfReaderBase class, I get an InvalidCastException because this.LastValue is trying to convert a string into ULong in the LastValueAsHandle property. This is a result of the Style
property in the MText Entity: https://github.com/DomCR/ACadSharp/blob/master/ACadSharp/Entities/MText.cs. The DfxCodeValue Attribute is set to Handle. As a result, it is trying to convert the string "Bold" to a ULong handle. Changing the DfxCodeValue attribute to Name fixes this.
Originally posted by @gktval in #63 (comment)
Is your feature request related to a problem? Please describe.
No, it's a feature request.
Describe the solution you'd like
I want to load only specific type of entity, using less time to read the DWG.
The main goal mine is read the attributes from inserted blocks.
This is the drawn polygon in cad file.
And this is the output shape after reading it using ACadSharp:
and there isn't any indicator for the arc segment like [Center, startAngle, endAngle, Radius]
I think there is a bug in reading polygon contains arc because I tried to read an arc shape [a separate arc ] like this:
While working on DXF & DWG files in which the content is the same, I've noticed that the DWG reader reads angle values in radians (as documented) I have a branch which shows these differences in MText, TextEntities, Arcs & Ellipses.
TextEntities show degrees on the DXF & Arc start and end angles. All others are radians. I was just going to make a PR, but I thought it would be worth discussing. the DWG documentation rightfully states that the angle values will be in radians but the DXF is a little less explicit by stating "angle" for several types.
netDXF handles this by ensuring all the angles are in degrees, but it seems that most of the angles in the files are actually in radians. Do we want to just convert everything to make sure it's in radians during the reading process?
Angle DXF & DWG written in AutoCAD 2010 formats.
angles.zip
A side note is that the MText rotation is not being read by either. I'll open a separate issue for this.
Output of the dwg-dxf-angles branch:
DXF TextEntity Rotation: 45
DWG TextEntity Rotation: 0.7853981633974483
DXF Ellipse StartParameter: 1.020388469764473
DWG Ellipse StartParameter: 1.0203884697644738
DXF Ellipse StartParameter: 1.570796326794896
DWG Ellipse StartParameter: 1.5707963267948966
DXF Arc StartAngle: 45
DWG Arc StartAngle: 0.7853981633974483
DXF Arc EndAngle: 90
DWG Arc EndAngle: 1.5707963267948966
DXF MText Rotation: 0
DWG MText Rotation: 0
I would like to thank you for your work on this project. Developing a DXF/DWG interface is a whole lot of work as the format has evolved so much over the years and has many dark corners and black boxes. I see that this project is primarily a DXF (binary & text) project but I see that you are also working on a DWG writing branch.
The DWG format is proprietary and this has stifled innovation in this area for so many years. LibreCAD is GPL so that code is essentially untouchable for anything commercial, AutoDesk licenses their DWG software out on a subscription and the ODA has its own pitfalls.
If an open source DWG file editor was available, I feel that this would be something that could be really revolutionary for people consuming DWG files.
What would you like in support to further pursue this area of DWG reading/writing development?
Dear all,
I am using this library to read some dwg files.
I have been able to read almost all the entities in the file, but I am having issues with the Insert Entities.
What I need is to understand how to position entities in the Insert type correctly in the world.
Now seems that all related entities are positioned well, but rotated some kind of 90 degrees
`
EntityTransform transform = new()
{
Rotation = (float)insert.Rotation,
Scale = new((float)insert.XScale, (float)insert.YScale),
Translation3d = new((float)insert.InsertPoint.X, (float)insert.InsertPoint.Y, (float)insert.InsertPoint.Z),
};
transforms_[transformCount] = transform;
foreach (Entity entity in insert.Block.Entities)
{
if (insert.Normal.Z == -1)
{
transform.Rotation *= -1;
transform.Scale = new(-(float)insert.XScale, (float)insert.YScale);
transform.Translation3d = new((float)-insert.InsertPoint.X, (float)insert.InsertPoint.Y, (float)insert.InsertPoint.Z);
}
ExportEntity(entity, layer, transforms_);
}`
I am using the quoted code, where insert is my insert entity.
I am transforming the entities by father, but rotation is bugged (and some entities are pixels away from their position).
Which is the right code to calculate it? I am not able to find any useful example online
The following images show result, first one is from Autodesk DWG TrueView
this one is from my code...
Thank you for any help, will be appreciated
Describe the bug
I have two dwg files with difference draw order of two objects
To Reproduce
Parse two file and serialize to JSON. There is no difference except for modification date. They have the same draw order.
Expected behavior
I think these object should have different position in Objects array.
using ACadSharp;
using ACadSharp.IO;
using Newtonsoft.Json;
void onNotification(object sender, NotificationEventArgs e)
{
Console.WriteLine(e.Message);
}
CadDocument doc = DwgReader.Read("./draworder.dwg", onNotification);
var json = JsonConvert.SerializeObject(doc, new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
});
await File.WriteAllTextAsync("output1.json", json);
Correct me if i test it wrong.
To Reproduce
This is my dxf file: 1.zip
Expected behavior
I have some entities in the 'Insert' entity, but can not get the right result, something I do wrong?
Screenshots
Additional context
Add any other context about the problem here.
If the issue is related to an specific dwg/dxf file and if able, attach that file to the issue of an equivalent with the same error.
Hello,
Good Work on that project.
there is a problem with its speed.
with my best regards.
We are using this very fine library to write a DWG-to-SVG converter preserving DWG structures such as BlockRecords.
We need to read MULTILEADER entities. A reader for MULTILEADER entities is currently not available.
We started implementing readers by creating a reader for MULTILEADERSTYLE objects. We are getting more and more into it and found that it was quite easy to understand after all.
The MULTILEADER entity, however, contains sbstructures such as CONTEXT_DATA {} and a list of LEADER objects etc.
Can anyone give a hint how to start reading a substructure.
Hatch.BoundaryPath.Ellipse
is used to describe an edge in a boundery path for the Hatch entity.
The ratio of minor to major axis is stored with DXF group code 40.
This value is read into the Radius
property. This is, I suppose, not intended. The Radius
property has no relevance for an elliptical art.
The DXF documentation states that is the ratio in percent. This seems, however, not to be true.
Anyhow - the value should be stored into MinorToMajorRatio
property.
Describe the bug
The attached dxf loads in True View, but throws an exception on DxfReader.Read()
To Reproduce
Try loading the DXF (zipped)
DXF file:
out of range error.zip
Thank you Dom!
This error occurs while opening the attached DWG file. Thanks.
11katli.zip
System.IndexOutOfRangeException: 'Index was outside array bounds.'
Describe the bug
The arc entities are not handled correctly throughout the AcadSharp library.
All the files contain 2 arcs with the same starting point and bulge but with different end point:
The files should have the same entities with the same values.
To Reproduce
Example 1:
DwgReader
Input.dwgDxfWriter
Code:
ACadSharp.CadDocument loaded = ACadSharp.IO.DwgReader.Read("Input.dwg");
ACadSharp.IO.DxfWriter.Write("Output.dxf", loaded, false);
Example 2:
CadDocument
DxfWriter
Code:
ACadSharp.CadDocument doc = new ACadSharp.CadDocument();
doc.Entities.Add(ACadSharp.Entities.Arc.CreateFromBulge(new CSMath.XY(100, 100), new CSMath.XY(200, 200), 1));
doc.Entities.Add(ACadSharp.Entities.Arc.CreateFromBulge(new CSMath.XY(100, 100), new CSMath.XY(150, 150), 1));
ACadSharp.IO.DxfWriter.Write("Output2.dxf", doc, false);
Expected behavior
I expect the two Output files to be as the Input one.
Additional context
Files.zip
AcadSharp up to date with master branch at b17c7df
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.