Sunday, December 10, 2023

Python for AutoCAD, Using shapely to find an oriented bounding box.

 

I see this asked frequently in the AutoCAD forums “How do I get the bounding box of an entity”, and the standard answer is usually, “Use vla-GetBoundingBox”, or get the entity extents. This is the correct answer, caveat, the bounding box is aligned with WCS, so if your object is rotated the result may not be what you need.

 One option is to transform the object to align with WCS. Or we can use a 3rd party tool like Python’s shapely to help. 

 

here's an example:

import traceback
from pyrx import Ap, Ax, Db, Ed, Ge, Gi
from shapely import LineString


@Ap.Command()
def mybb() -> None:
    try:
        # create a selection set filter and select the polylines
        filter = [(Db.DxfCode.kDxfStart, "LWPOLYLINE")]

        ps, ss = Ed.Editor.selectPrompt("\nSelect parts: ", "\nRemove parts: ", filter)
        if ps != Ed.PromptStatus.eNormal:
            return

        # iterate the selection set
        for id in ss:

            # create a LineString from our polylines
            pline = Db.Polyline(id)
            ls = LineString(pline.toList())

            # get the oriented bbox
            coords = ls.oriented_envelope.exterior.coords

            # convert tuples to Ge.Point3d
            points = [Ge.Point3d(p) for p in coords]

            # #draw the results
            Ed.Core.grDraw(points[0], points[1], 1, 0)
            Ed.Core.grDraw(points[1], points[2], 1, 0)
            Ed.Core.grDraw(points[2], points[3], 1, 0)
            Ed.Core.grDraw(points[3], points[0], 1, 0)
    except Exception as err:
        traceback.print_exception(err)




 


 


 

No comments:

Post a Comment

TraceBoundary sample in Python for AutoCAD

    import traceback from pyrx import Ap , Db , Ed , Ge , Gi @ Ap . Command () def TB () -> None :     try :         db = Db . curD...