Jump to content

Python, Extract Polyline Lengths with Associated Text Labels in AutoCAD


Recommended Posts

Posted

sample of this

 

import traceback
from pyrx import Db, Ed, Ge, Ap, Rx, Gs


@Ap.Command()
def doit():
    try:
        # select
        db = Db.curDb()
        filter = [(Db.DxfCode.kDxfStart, "TEXT,LWPOLYLINE")]
        ps, ss = Ed.Editor.select(filter)
        if ps != Ed.PromptStatus.eOk:
            raise RuntimeError("Selection Error! {}: ".format(ps))
        texts = [Db.Text(id) for id in ss.objectIds(Db.Text.desc())]
        plines = [Db.Polyline(id) for id in ss.objectIds(Db.Polyline.desc())]

        # make kdtree & list of points
        pntmap = {}
        plpoints = []
        for pl in plines:
            plpoints.append(pl.getStartPoint())
            plpoints.append(pl.getEndPoint())
            pntmap[pl.getStartPoint()] = pl
            pntmap[pl.getEndPoint()] = pl

        # search closest pline
        results = []
        tree = Ge.Point3dTree(plpoints)
        for text in texts:
            idxs, _ = tree.knnSearch(text.position(), 1)
            pl: Db.Polyline = pntmap[plpoints[idxs[0]]]
            results.append([text.textString(), pl.getDistAtParam(pl.getEndParam())])

        # format mtext
        results = sorted(results, key=lambda x: int(x[0][2:]))
        buffer = "{:<6}\t{}\\P".format("S.No", "Length Ft")
        buffer += "".join(f"{sno:<6}\t  {plen:>.2f}\\P" for sno, plen in results)

        # make mtext, add to currentSpace
        ps, pnt = Ed.Editor.getPoint("\nPick Text Position")
        mt = Db.MText()
        mt.setDatabaseDefaults(db)
        mt.setLocation(pnt)
        mt.setContents(buffer)
        cs = db.currentSpace(Db.OpenMode.kForWrite)
        cs.appendAcDbEntity(mt)

    except Exception as err:
        traceback.print_exception(err)

 

our.png.dce00c082023db3ec790bec133e4c259.png

Posted (edited)

Would a table answer be perhaps neater than Mtext ? Just ask for text size for table.

Edited by BIGAL
Posted

Yep, easier too, since there would be not need to format the string for MText.

Even though Python has robust string operations, it’s still weird to get it perfect

https://docs.python.org/3/library/string.html

 

I was just following along the original sample. The part I wanted to illustrate was, using a hashmap for mapping points to objects, and using the KD-Tree to do the spatial search 

 

I wrote the same KD-Tree and map for AutoLISP, I’m just really bad at lisp, so it’s hard for me to make samples lol

https://github.com/CEXT-Dan/ads_geo

 

  

 

Posted (edited)

Just a comment done  a lot of find object next to text, just used get text insertion point, then use "ssget "F" pts" the pts are say 10 points made via a polar defun looking like a circle . I noticed you go the other way around looking around the pline for the text.

 

Would be good to get a true sample dwg.

Edited by BIGAL
Posted

Yeah, I chose to search for the closest polyline to the text. BricsCAD has ssget crossing circle , (ssget "CC" point1 point2), could be similar to a radius search. Caveat, you’d have to call ssget for every mtext

 

 

There’s a .DWG in the original post in the lisp forums

Posted

I used a similar approach here, the user wanted to set the elevation of the contour lines to the nearest label.  This is where KD-Trees really start to shine as they can handle millions of points, with millions of searches

 

ct2.png.1fae9a0275faa0ebc9100b1106228ca8.png

 

ct1.png.a9814ba4999c9a222c1b2bd3dd16e34c.png

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...