libopencad

repository·master·Indexed 42 days ago

https://github.com/sandyre/libopencad

An open-source C++ library for reading and interacting with CAD files, specifically the DWG R15 format. It provides tools to extract geometry, layers, headers, and custom classes, featuring a comprehensive set of CAD geometry types (such as CADCircle, CADLine, and CADPolyline) and a dictionary system for managing CAD data.

Tokens
8.3K
Snippets
26
Records
43
Agent score
52%

What's inside libopencad

  1. Install libopencad via dynamic library

    master

    To use libopencad as a dynamic library, run cmake with the BUILD_SHARED_LIBS=ON flag, then build with make. The resulting dynamic library will be located in the lib/ directory with the version number in its filename.

    To integrate it into your project, link against the generated dynamic library and include the associated header files like opencad_api.h and cadgeometries.h.

    git clone https://github.com/sandyre/libopencad
    cmake -DBUILD_SHARED_LIBS=ON CMakeLists.txt
    make -j4
  2. Install libopencad via static library

    master

    To use libopencad as a static library, clone the repository, run cmake, and build using make. The resulting static library will be located in the lib/ directory with the extension appropriate for your OS (e.g., .a).

    To integrate it into your project, link against libopencadstatic and include the necessary header files such as opencad_api.h and cadgeometries.h.

    git clone https://github.com/sandyre/libopencad
    cmake CMakeLists.txt
    make -j4
  3. Understand the CADObject hierarchy

    master

    The library uses a hierarchical class structure to represent CAD entities:

    1. CADObject: The base class for all objects. It contains metadata like size, type (an ObjectType enum), and CRC.
    2. CADEntityObject: Inherits from CADObject. It is the base class for actual drawing entities and contains two critical structures:
      • stCed (CADCommonED): Contains extended entity data (ED), graphics data, and layer/color information.
      • stChed (CADCommonEHD): Contains handles to related objects like the owner, layer, LType, and previous/next entities in the database.
    3. Specific Entity Classes: Classes like CADTextObject, CADLineObject, and CADCircleObject inherit from CADEntityObject and add geometry-specific properties.
  4. Use the CADFileIO abstract class for file operations

    master

    The CADFileIO class is an abstract base class used to perform input/output operations (read, write, seek, etc.) on CAD files. To use it, you must implement a concrete subclass that provides the actual file handling logic for specific formats or file systems.

    Key Capabilities

    • Opening/Closing: Manage file access using Open(int mode) and Close().
    • Reading/Writing: Use Read(void * ptr, size_t size) for raw data and ReadLine() for text-based reading.
    • Positioning: Navigate the file using Seek(long int offset, SeekOrigin origin), Tell() to get the current position, or Rewind() to return to the start.
    • Status: Check if a file is open via IsOpened() or if the end of the file has been reached via Eof().
    class MyCADFileIO : public CADFileIO {
    public:
        MyCADFileIO(const char* filename) : CADFileIO(filename) {}
        // Implement virtual methods: ReadLine, Eof, Open, Seek, Tell, Read, Write, Rewind
    };
    
    // Usage:
    MyCADFileIO file("example.cad");
    if (file.Open(CADFileIO::read)) {
        // perform operations
        file.Close();
    }
  5. Understand the CADGeometry base class and types

    master

    All geometric entities in the library inherit from CADGeometry. This base class provides common attributes such as thickness, color (RGBColor), block attributes, and Extended Entity Data (EED).

    Supported GeometryType values include:

    • POINT, CIRCLE, LINE, ARC, ELLIPSE, SPLINE
    • LWPOLYLINE, POLYLINE2D, POLYLINE3D, POLYLINE_PFACE
    • TEXT, MTEXT
    • SOLID, FACE3D
    • RAY, XLINE
    • HATCH (Not implemented), IMAGE
    • MLINE, ATTRIB, ATTDEF
  6. Use libopencad to read and inspect CAD files

    master

    You can use OpenCADFile to load a CAD file. If the function returns nullptr, you can retrieve the error details using GetLastErrorCode().

    Once a file is opened, you can access:

    • CADHeader: Use getHeader() to get header information and print() to display variables.
    • CADClasses: Use getClasses() to retrieve custom CAD classes.
    • Layers: Iterate through layers using getLayersCount() and getLayer(i). Each layer contains geometries that can be accessed via getGeometry(j).
    #include <iostream>
    #include "lib/opencad_api.h"
    
    // returns nullptr on fail. GetLastErrorCode() returns an error code.
    CADFile *pCADFile = OpenCADFile( pszCADFilePath, 
                                    CADFile::OpenOptions::READ_ALL );
    
    if (pCADFile) {
        const CADHeader& header = pCADFile->getHeader ();
        header.print ();
    
        const CADClasses& classes = pCADFile->getClasses ();
        classes.print ();
    
        for ( size_t i = 0; i < pCADFile->getLayersCount (); ++i ) {
            CADLayer &layer = pCADFile->getLayer (i);
            for ( size_t j = 0; j < layer.getGeometryCount (); ++j ) {
                unique_ptr<CADGeometry> geom(layer.getGeometry (j));
                if ( geom == nullptr ) continue;
    
                switch ( geom->getType() ) {
                    case CADGeometry::CIRCLE:
                        CADCircle * poCADCircle = ( CADCircle* ) geom.get();
                        std::cout << poCADCircle->getPosition().getX() << std::endl;
                        break;
                }
            }
        }
    }
  7. Retrieve CAD file metadata and structures

    master

    The CADFile class provides read-only access to the core components of the parsed document:

    • getHeader(): Returns a const CADHeader& containing file metadata.
    • getClasses(): Returns the CADClasses object.
    • getTables(): Returns the CADTables object.
  8. Add handles to CADLayer

    master

    You can associate specific CAD object handles with a CADLayer using the addHandle method. This is useful for mapping entities to the layer, including distinguishing between entities in the ModelSpace and those within custom blocks.

    void addHandle(long handle, enum CADObject::ObjectType type, long cadinserthandle = 0)

    • handle: The primary CAD object handle.
    • type: The CADObject::ObjectType of the entity.
    • cadinserthandle: (Optional) The handle of the CAD insert if the entity is part of a custom block. Defaults to 0 (representing ModelSpace).
    // Adding a handle for an object in ModelSpace
    layer->addHandle(12345, CADObject::ObjectType::LINE);
    
    // Adding a handle for an object that is part of a block reference
    layer->addHandle(67890, CADObject::ObjectType::CIRCLE, 54321);
  9. Manage CAD tables with the CADTables class

    master

    The CADTables class is used to store and manage various CAD-related tables (such as layers, blocks, and styles) within a CAD file. It provides methods to add, retrieve, and read these tables from a CADFile object.

    Supported Table Types

    The CADTables::TableType enum defines the following supported tables:

    • CurrentViewportTable
    • BlocksTable
    • LayersTable
    • StyleTable
    • LineTypesTable
    • ViewTable
    • UCSTable
    • ViewportTable
    • APPIDTable
    • EntityTable
    • ACADGroupDict
    • ACADMLineStyleDict
    • NamedObjectsDict
    • LayoutsDict
    • PlotSettingsDict
    • PlotStylesDict
    • BlockRecordPaperSpace
    • BlockRecordModelSpace
  10. Work with Attributes and Attribute Definitions

    master

    CADAttrib

    Represents an attribute attached to a block.

    • setTag(const string&): Sets the attribute tag.
    • setAlignmentPoint(const CADVector&): Sets the insertion/alignment point.
    • setPositionLocked(bool): Determines if the position can be changed.

    CADAttdef

    Represents an attribute definition (the template for an attribute).

    • setPrompt(const string&): Sets the user prompt for this attribute.
  11. Work with Splines

    master

    The CADSpline class manages complex curves using control points and fit points.

    • addControlPoint(const CADVector&): Adds a control point.
    • addFitPoint(const CADVector&): Adds a point the curve must pass through.
    • setDegree(long): Sets the spline degree.
    • setRational(bool): Enables/disables rational spline behavior.
    • setClosed(bool): Closes the spline loop.