AutoCAD®, VB and Mathematics

If you want to become an expert AutoCAD® script writer, at some point you’re going to need to know a bit about maths, or at least have the capacity to learn. It doesn’t have to calculus, but stuff like Pythagoras theorem and trigonometry are very much your friend in a geometric environment such as AutoCAD®. Cringing yet? Don’t worry – often it’s not as difficult as it seems.

I’ve been asked how to replicate the measure command along an arc – there is no real simple answer (that I can think of). The way I would do it is through actually calculating the points in 2D space. This may sound tricky, but languages such as VB really are conducive to this kind of work, and you may be surprised how simple this actually is.

So for the purposes of this post I will be showing you how to calculate and draw a circle of points using VBA. Obviously an arc is merely just part of a circle, so isn’t really any different. Although we’re using VBA for convenience, the rationale behind the exercise will work in any programming language.

Step One – Get it clear in our minds

Logically, to define a circle in 2D space, you need to know the centre for the circle, and the radius. It’s no coincidence then that this is exactly what is required by the CIRCLE command in AutoCAD.

To define a point on the circumference of that circle then – if you have defined your circle, all you need is an angle. From that angle, we can logically derive the point on the circle at that angle. So in our minds at least, we know how to define a point on the circumference of a circle using a centre for the circle, a radius, and an angle.

Now we have to convert that logic into code.

Step Two – Understand Sine and Cosine

One of the key things that will be at work here will be the use of the trigonometric functions sine and cosine. I think it is worth delving into what these actually mean, as understanding this can be very helpful for this kind of work. In fact, when I was at school I was taught parrot-fashion how to use SOH-CAH-TOA to work out which trig function to use for which situation. I’ve never been a fan of that kind of “learning”. I like to understand the underlying principles so that I can apply them to any situation, but sadly I was never taught in that way. My own curiosity led me to figuring out the diagram below for myself, and it really enhanced my ability to understand trigonometry, and what sine and cosine actually are.

Consider the image below:


Assuming a hypotenuse (the angled lines coming from the centre) length of 1, sine is the length of the deflection in the Y axis for a given angle. So in the example above, a line drawn at 30°  a length of 1, will produce a deflection in the Y axis of 0.5. Sine 30 = 0.5. It’s as simple as that.

Cosine is equally as simple, but rather than the deflection in the Y axis, it will return the deflection in the X axis. So, Cosine 30 = 0.866.

This is how we are able to determine the length of sides in a triangle from angles through trigonometry. Lets assume the hypotenuse is actually 4. The ratio between the sides is still the same, so the calculation to work out the vertical edge of the triangle (the deflection in the Y axis) is as simple as 4 * Sin 30. We multiply by the length of the hypotenuse to scale the side length to the correct size. Simples.

Step Three – Write the code

I think we’re ready for some code. Below is a function that accepts the various inputs we have identified and will draw a point in modelspace.

Sub drawPointOnCirc(xPos As Double, yPos As Double, radius As Double, angle As Double)
Dim insertPoint(2) As Double
Dim xOffset As Double
Dim yOffset As Double
Dim angleRadians As Double
Const PI As Double = 3.14159265358979

'Convert degrees to radians, as required by VBA trig functions
angleRadians = 2 * PI * angle / 360

'Calculate the X and Y offset from the centre of the circle
xOffset = Cos(angleRadians) * radius
yOffset = Sin(angleRadians) * radius

'Add the circle centre to the offset values, to get the absolute
'position of the point on the circumference of the circle.
insertPoint(0) = xPos + xOffset
insertPoint(1) = yPos + yOffset

ThisDrawing.ModelSpace.AddPoint insertPoint

End Sub

This function is actually really useful to us now. We are able to draw a point in modelspace that represents a location on the circumference of a circle. Now, if we were to call the function in the manner below:

Sub main()
Dim n As Double
For n = 1 To 120
drawPointOnCirc 10, 10, 3, n
Next
End Sub

this would draw 120 points at 1 degree intervals along an arc. The circle centre is defined at 10,10 with a radius of 3, which is what the arc should show.

And that’s it!

Hopefully this post has shown you how a little bit of maths can be helpful – the production and reuse of functions like this is really helpful to building up more complex applications… have fun, and as always, feel free to get in touch if you have any problems.

And please subscribe below if you want more tips like this!

Will

How to Control AutoCAD® From a Standalone Executable

I’ve had a few requests recently to do a post on creating executables that control AutoCAD®. Though generally it is better to have tools well integrated into AutoCAD® via the use of a NETLOADed dll for example, sometimes an exe can be an elegant solution.

The general concepts are fairly straight forward.

  1. Check for a running instance of AutoCAD®, and create a reference to it. If it is not running, launch AutoCAD®, and create a reference to it.
  2. Use COM to control AutoCAD

When I started that list, I expected it to be longer – but essentially that’s it. If you’re more of a VBA user, you’ll be very pleased to hear that as we’re using COM, you can pretty much re-use all the VBA code you ever learned.

So, lets draw a basic shape. Something like below:

random shape

Ok – this can easily be handled by a polyline, so this is what our exe will do.

First things first though. Create a new standalone exe project in VB. You can use VB.NET, or VB6 for this. You’ll not need to worry about targeting any specific .NET frameworks or anything like that. As we are using COM we are completely sidestepping those issues.

So I’m going to go ahead with VB6; a bit old-school, but it illustrates the point well. New Project > Standard EXE.

Firstly, we need to create a reference to AutoCAD® in our code. To do this, we need to load the relevant AutoCAD® types and libraries into our exe project. So, go to Project > References. From here you’ll want to select the AutoCAD® type libraries you want to use, depending on which version of AutoCAD® you’re using.

Once loaded, we can create variables that are typed for AutoCAD®, and we are now able to write our code. For the purposes of this example we’re not really interested in using the Form properly, we’re only really using it as a container for our code in the Load event:

Private Sub Form_Load()
Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
'On Error Resume Next 'This tells VBA to ignore errors
Set ACAD = GetObject(, "AutoCAD.Application") 'Get a running instance of the class AutoCAD.Application
'On Error GoTo 0 'This tells VBA to go back to NOT ignoring errors
If ACAD Is Nothing Then 'Check to see if the above worked
Set ACAD = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD
ACAD.Visible = True 'Once loaded, set AutoCAD® to be visible
End If

Dim llCorner As Variant
llCorner = ACAD.ActiveDocument.Utility.GetPoint(, "Pick the lower left corner for the shape")

'Draw shape in terms of the lower left corner
Dim coords(11) As Double
'lower left corner of shape
coords(0) = llCorner(0)
coords(1) = llCorner(1)
'lower right corner of shape
coords(2) = llCorner(0) + 100
coords(3) = llCorner(1)
'upper right corner of shape
coords(4) = llCorner(0) + 100
coords(5) = llCorner(1) + 30
'right hand corner of semicircle
coords(6) = llCorner(0) + 70
coords(7) = llCorner(1) + 30
'Draw the semicircle as a straight line for now. We will set the bulge on this segment later.
'left hand corner of semicircle
coords(8) = llCorner(0) + 30
coords(9) = llCorner(1) + 30
'upper left corner of shape
coords(10) = llCorner(0)
coords(11) = llCorner(1) + 30

'With the coordinates defined, use these to create a new polyline
Dim poly As AcadLWPolyline
Set poly = ACAD.ActiveDocument.ModelSpace.AddLightWeightPolyline(coords)
'Set the bulge of segment 4 of the polyline (ie, index 3) to a value of -1
poly.SetBulge 3, -1
'Close the polyline
poly.Closed = True

'End application
Unload Me

End Sub

So that’s how to draw this shape using a VB6 standalone. The method would be very similar for VB.NET, but you’ll need to take a slightly different approach when accessing the ThisDrawing object. This is discussed in my Introduction to VB.NET in AutoCAD.

Hope this helps someone, and I encourage you to join the hordes of people that have subscribed by filling out an email address below!

Will

Export Points from AutoCAD® to CSV file using VBA

Today I’m going to show you how to use a bit of simple VBA to export data to a CSV file. It’s really simple, and although there are other ways of achieving the same thing, this way allows great flexibility, and is very versatile.

Firstly, I’ll set up a drawing with a few points in it. These points will be what we will export:

Screenshot Of Points

The next step is to open the VBA editing window using the VBAIDE command. Of course, if you’re using AutoCAD® 2010+ you’ll need to download the VBA add-on. Once open, right click in the project explorer window and create a new module.

Now for the code. I was going to explain the code, but as I’ve commented it pretty well, I don’t really think I need to. Take note of the part about the FileSystemObject, as you’ll need to follow the instructions before the code will work. Do ask if you have any other questions.

Option Explicit

Sub ExportPoints()
    'Declare variables
    Dim currentSelectionSet As AcadSelectionSet
    Dim ent As AcadEntity
    Dim pnt As AcadPoint
    Dim csvFile As String
    Dim FSO As FileSystemObject
    Dim textFile As TextStream
    
    'Create a reference to the selection set of the currently selected objects
    Set currentSelectionSet = ThisDrawing.ActiveSelectionSet
    
    'Check if anything is selected, and give exit with a warning if not
    If currentSelectionSet.Count = 0 Then
        ThisDrawing.Utility.Prompt "There are no currently selected objects. Please select some points to export, and run this command again." & vbNewLine
    End If
    
    'Use a For Each statement to look through every item in CurrentSelectionSet
    For Each ent In currentSelectionSet
        'In here, ent will be one of the selected entities.
        
        'If ent is not a point object, we should ignore it
        If TypeOf ent Is AcadPoint Then
            'Only points will make it this far
            
            'Now that we know we are dealing with a point,
            'we can use the specific AcadPoint type of variable.
            Set pnt = ent
            'You'll notice that after doing this, you have more
            'intellisense methods when you type "pnt."
            
            'Add a line to the string variable csvFile.
            'We are concatenating two numbers together with a comma in between,
            'and adding a new line character at the end to complete the row.
            csvFile = csvFile & pnt.Coordinates(0) & "," & pnt.Coordinates(1) & vbNewLine
            
            'Saying that csvFile = csvFile & whatever is a useful
            'way to repeatedly add to the end of a string variable.
            
        End If
        
    Next
    
    'Write the contents of the csvFile variable to a file on the C:\ with the same name
    
    'FileSystemObjects are really useful for manipulating files
    'But, you'll need a reference to the Microsoft Scripting Runtime in your VBA project.
    'Go Tools>References, and select the Microsoft Scripting Runtime.
    
    'Create a new File System Object
    Set FSO = New FileSystemObject
    
    'Using FSO.CreateTextFile, create the text file csvFile.csv,
    'and store a reference to it in the variable textFile
    Set textFile = FSO.CreateTextFile("C:\csvFile.csv")
    
    'Write the string variable csvFile to textFile
    textFile.Write csvFile
    
    'Close textFile, as we are finished with it.
    textFile.Close
    
    'Alert the user that the file has been created
    ThisDrawing.Utility.Prompt "Points have been exported to C:\csvFile.csv" & vbNewLine
    
End Sub

And there we have it. You could of course add more conditions in there – say, nest another IF statement in the middle that filters out say only red points. It doesn’t have to be points either – this process will work with any properties of any AutoCAD® entity.

Have fun, and if you haven’t already, please do subscribe below!

Will

Excel and AutoCAD® – A match made in heaven – Part 3

One of my readers has requested some help regarding the drawing of windows. I’m not 100% sure of his exact requirements, but it’s a good opportunity for me to build on what I’ve already shown you. This will be a brief post – the main content of which is some annotated VB code (below). This simply takes the previous Excel and AutoCAD® post a little further by creating a practical implementation.

What this does is allows the user to enter an X,Y,Width and Height coordinate in Excel, in columns A,B,C and D respectively. Running the code draws them as rectangles in modelspace.

I’ve decided to compile this as an Excel file, which is downloadable below. It is worth mentioning that I have referenced a specific version of AutoCAD® in this file (Under Tools>References from the VBA editor accessible from Excel using Alt+F11). The code should work if you reference your own version of AutoCAD.

WindowMaker

The source code is here also for you to look at, or paste into your own project. Again, you’ll need to create a reference to AutoCAD® as explained in the previous article.

Sub Main()
Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
On Error Resume Next 'This tells VBA to ignore errors
Set ACAD = GetObject(, "AutoCAD.Application") 'Get a running instance of the class AutoCAD.Application
On Error GoTo 0 'This tells VBA to go back to NOT ignoring errors
If ACAD Is Nothing Then 'Check to see if the above worked
Set ACAD = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD
ACAD.Visible = True 'Once loaded, set AutoCAD® to be visible
End If
ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
Dim Coords(7) As Double 'This is an array of double precision floating point numbers

Dim n As Integer 'Create the variable n as the type Integer
For n = 1 To 10 'Loop this code, incrementing the value of n from 1 to 10

'Variables for X,Y,Width and Height
Dim X As Double
Dim Y As Double
Dim Width As Double
Dim Height As Double

'Store the values from Excel in memory - We could just use Sheet1.Cells(), but
'this makes it much more readable for us as programmers, and it is faster to retrieve
'data from variables than from the worksheet.
X = Sheet1.Cells(n, 1)
Y = Sheet1.Cells(n, 2)
Width = Sheet1.Cells(n, 3)
Height = Sheet1.Cells(n, 4)

'Lightweight polylines are defined by a series of 2D coords in an array

'Bottom Left Corner
Coords(0) = X
Coords(1) = Y

'Bottom right Corner
Coords(2) = X + Width
Coords(3) = Y

'Top Right Corner
Coords(4) = X + Width
Coords(5) = Y + Height

'Top Left Corner
Coords(6) = X
Coords(7) = Y + Height

'Create a polyline-type variable - its initial value will be empty (non-existent)
Dim PL As AcadLWPolyline

'Create a polyline based on these coordinates
'The Set statement is used when creating a reference to objects (complex data types)
'The value of PL will be a reference to our new polyline
Set PL = ACAD.ActiveDocument.ModelSpace.AddLightWeightPolyline(Coords)   'Add a point in AutoCAD® at this location

'Make PL a closed polyline
PL.Closed = True

Next
End Sub

Hope this helps! And if you want to reap the benefit of spectacular hints and tips like this regularly, subscribe below! Not to mention my outstandingly witty writing style…errmm…so yes please do subscribe!
Will

Join The Dots – How To Create VB.NET AutoCAD® Tools

Been struggling to find time to post on here recently due to exams, work and planning a wedding… with a bit of a lull in between everything, now’s a good time to get back in the swing of it!

Join The Dots – what on earth am I talking about?! Its the name I’ve given to a script I’ve been planning on writing for a while. It is a relatively simple idea, so I am going to take the opportunity to do a step-by-step walkthrough for writing a new AutoCAD® tool.

Preliminary Design

The first thing, is to have an idea. This sounds obvious, but having a clear idea is very important. Writing code will produce specific and predictable results, so you need to know exactly what you want to achieve.

Join The Dots is going to be a tool that will take a series of points, and will draw a polyline through every point, representing the shortest path (hopefully!).

The first step is to think about the idea. I usually ask myself the question “how would you achieve this manually?”

If you didn’t join up the dots in a specific way, you’d no doubt end up with situations like this:

Longest Path
Longest Path

This is in fact the longest path. After thinking about it a bit, I thought that you could start off by finding the shortest distance between any two points. This could form a starting segment for our polyline, and then we could append vertices to the line based on their proximity to the start and end points.

Basically, find the shortest line:

Shortest Path Step 1
Shortest Path Step 1

Then, look for the next closest point to one of the endpoints of the line:

Shortest Path Step 2
Shortest Path Step 2

Repeat:

Shortest Path Step 3
Shortest Path Step 3

And we’ve found the shortest path. So, we have a plan for how to create the tool – time to do some techie stuff!

Setting Up The Project

In my experience thus far, VBA was a lot simpler for interacting directly with AutoCAD®. With .NET, we need to interact with the document database, which is a tad more complex, and involves a bit more code to achieve the same thing.

Ok, firstly we need to set up our project. I’ve already created a template for AutoCAD® applications, so I’ve selected that. Using .NET you will need to set up your project correctly – if you want an easy way to set things up, read through this very short tutorial on setting up a VB.NET template that works with AutoCAD.

Coding The Design

Step 1 – Create a selection

Once we’ve set up the project, the first step in our application is to make a selection that we can use later. We want the user to be able to select the points that are to be used in the JoinTheDots command. The code below goes in your main subroutine – if you’re not sure how things glue together, don’t worry – the full code will be given at the end.

'Setup
Dim ed As Editor = Application.DocumentManager.MdiActiveDocument.Editor

'Declare our filter entries this way
Dim values() As TypedValue = {
New TypedValue(DxfCode.Start, "POINT")
}

'Create the filter using our values
Dim sfilter As New SelectionFilter(values)

'Set the selection options
Dim SelOpts As New PromptSelectionOptions()
SelOpts.MessageForAdding = "Select points to find the shortest path through"
SelOpts.AllowDuplicates = True

'Make the selection
Dim res As PromptSelectionResult = ed.GetSelection(SelOpts, sfilter)

'If the user did something other than make a selection (like pressing ESC), then abort
If Not res.Status = PromptStatus.OK Then Return

'Create a selection set based on the user's selection
Dim ss As Autodesk.AutoCAD.EditorInput.SelectionSet = res.Value

'Create an array of object IDs from the selection set, so that we can loop through them easily
Dim idarray As ObjectId() = ss.GetObjectIds()

So firstly we’re creating the variable ed, which refers to an object known as the Editor. This has many useful functions that we will use later.

Next, we’re going to create a filter that we will use to limit what the user can select. After all, we’re trying to “Join The Dots”, so we only want the user to be able to select AutoCAD® POINTs.

The next step is to ask the user to make a selection – however in order to do that we need to set up some things first. We need to set some PromptSelectionOptions, such as the message we want to display to the user. After these settings have been initialised, we can use the SelOpts variable which contains these settings, and the sfilter variable which contains our filter, to invoke the GetSelection method of our Editor object. This will give the user the opportunity to select any objects on screen, and the result of the user’s actions will be stored in the res variable, which contains a PromptSelectionResult object.

We need to be mindful to any possible action that the user might take. For example, the user might press the Escape key. If this happens, we need to know, and do something else. This is where capturing the result in the res variable is useful. We’re able to tell using res.Status, what type of input the user gave us. If res.Status is “OK”, then we know that the user made a selection as expected. If anything else happened (in other words, if the status is NOT “OK”), then the user did not make a selection as required, and we should exit the subroutine through the Return statement.

Finally, if the user made a selection, we want to convert that into a format that is more useful to us – a selection set. Then, from the selection set, we will retrieve the ObjectIds of the objects that were selected. That way, we are able to retrieve and use the individual entities that were selected at some point later on in our code.

Step 2 – Using Transactions

Developing for AutoCAD® using .NET requires that we wrap any modifications to the document in transactions. To make changes to anything in the drawing we need to start a transaction, make changes to the drawing, add these changes to the transaction, commit the transaction, and then dispose of the transaction. This is perhaps a bit long winded, but is actually inherently has some neat perks. One example is that the AutoCAD® UNDO command will undo the whole transaction rather than individual changes. Another example, is that if there is an error at some point in your code (heaven forbid!!) the whole transaction will be voided, and you’re not left with a drawing that has been half messed with, and half the same as before.

But anyway, you need to use a transaction – and here’s how it’s done:

'Create a link to the active document's database
Dim db As Database = Application.DocumentManager.MdiActiveDocument.Database
'Create a transaction manager object
Dim tm As Autodesk.AutoCAD.DatabaseServices.TransactionManager = db.TransactionManager
'Start a transaction
Dim myT As Transaction = tm.StartTransaction()

'DO STUFF HERE!

'Commit the transaction
myT.Commit()
'Dispose of our transaction
myT.Dispose()

So the first step is to create the variable db which refers to the database of the active document. Next, we create the variable tm, which refers to db.TransactionManager. Then, its just a case of invoking tm.StartTransaction, and storing the resultant Transaction object in the variable myT. Easy huh?

After “DOING STUFF!”, we simply Commit the transaction, then Dispose of it. Changes should then be visible in your drawing (assuming you did make changes!!).

Step 3 – Make Changes To The Drawing

'Create a coord array, the same size as the idarray
Dim points(idarray.GetUpperBound(0)) As DBPoint
'Populate the coord array with point2d objects representing the location of the DBPoint objects
Dim n As Long
For n = 0 To idarray.GetUpperBound(0)
points(n) = tm.GetObject(idarray(n), OpenMode.ForRead, True)
Next

'Find the shortest line formed by two coordinates, create a polyline representing this line, and
'remove the two coordinates from the coords array
Dim pl As Polyline = GetShortestLine(points)

Dim TimeToExit As Boolean = False
Do
TimeToExit = AppendPoint(pl, points)
Loop Until TimeToExit

'Add the polyline to modelspace
AddToModelSpace(db, myT, pl)

If you were thinking it were as simple as the code above – I’m sorry to disappoint you… This code calls a few other functions, so we’ll be looking at those seperately, but the abstract idea for “making changes to the drawing” is as follows.

  • Firstly, get a list of all the DBPoints. To do this, we’ll loop through all the ids in our idarray, and add each DBPoint object to a new array called points().
  • Now, find the two points that are closest together, and we will use those two points to create the first segment of our polyline. This is what the GetShortestLine function does.
  • Now we want to add the remaining points to the polyline, using the point that is closest to one of the ends of the polyline. We want to repeat this step until there are no points remaining.
  • Finally, we need to add the polyline (in the variable pl) to the transaction.

And that’s the high level process. Specific tasks like getting the shortest line, and appending a point the the polyline, are useful to separate from the main subroutine. This makes it much more readable – we can see the high level process, without getting confused with the detail.

Step 4 – Get the shortest line

This code isn’t as complicated as it looks – honest!

Private Function GetShortestLine(ByRef points() As DBPoint) As Polyline

Dim n As Long
Dim m As Long

'Info that needs to be captured
Dim basePoint As DBPoint
Dim endPoint As DBPoint
Dim shortestDist As Double = 1.0E+300 'A very very big number!

'Loop through every combination of point pairs, and find the pair with the shortest distance
For n = 0 To points.GetUpperBound(0)
For m = n + 1 To points.GetUpperBound(0)

Dim tmpDist As Double
tmpDist = points(n).Position.DistanceTo(points(m).Position)

'If this is the shortest distance so far, update
If tmpDist < shortestDist Then
shortestDist = tmpDist
basePoint = points(n)
endPoint = points(m)
End If

Next
Next

'Add the points forming the shortest distance to a new polyline
Dim pl As Polyline = New Polyline
pl.AddVertexAt(0, basePoint.Position.Convert2d(New Plane), 0, 0, 0)
pl.AddVertexAt(1, endPoint.Position.Convert2d(New Plane), 0, 0, 0)

'remove basePoint and endPoint from the array of points, so that they are not reused
RemovePoint(points, basePoint)
RemovePoint(points, endPoint)

Return pl
End Function

Basically, what this function does is iterates through every point, and measures the distance from that point to every other point. The shortest distance found will be remembered, along with the two points that form the shortest distance. The main mechanism at work here is a combination of two For Next loops. The first For Next loop iterates the value of n between 0 and the upper bound of points array. So if there are 10 points, n will loop between 0 and 9. The second For Next loop iterates the value of m between the value of n + 1, and the upper bound of the points array. So, in the case of n=0, m would loop from 1 to 9. This is so that we only make new comparisons – for example, we wouldn’t want to compare points(0) with points(0), as its the same point. So we start the inner loop at n+1. We want the combination of n and m to always be unique, and cover every combination. This is what the pair of For Next loops achieves.

After the For Next loops have completed, we have found the points that create the shortest distance. What we want to do now, is create a polyline based on these two points. What we do, is create a new polyline object, and simply add the vertices to the polyline, at the correct positions, i.e., at 0 for the basePoint, and 1 for the endPoint. This creates a polyline joining up the two points.

Finally, so that in future we do not use these points any more as they are already within our polyline, we want to remove them from the points() array. Here we are using another function to do that.

Step 5 – Remove Item From An Array in VB.NET

There is no native function for removing an item from an array in VB.NET, so we will have to create a function to do this ourselves. It’s a fairly simple idea:

Remove Item From Array
Remove Item From Array

So, we loop from 0 to the upper bound of the array, and when we get to the item number we want to remove, we simply overwrite it with the next value in the array, and keep overwriting each subsequent item from this point.

Here’s the code:

Private Function RemovePoint(ByRef points() As DBPoint, ByRef remPoint As DBPoint) As Boolean
Dim n As Long
Dim newUpperBound As Long = points.GetUpperBound(0) - 1
Dim pointFound As Boolean
'Iterate through the points array until the removePoint is found, then nudge points down the array
For n = 0 To newUpperBound
If Not pointFound Then
If points(n) Is remPoint Then
pointFound = True
End If
End If
If pointFound Then
points(n) = points(n + 1)
End If
Next
'Set the new size of the array, clipping off the last item of the array
ReDim Preserve points(newUpperBound)

If newUpperBound = -1 Then
Return True
Else
Return False
End If

End Function

The final stage in this code is to simply re-dimension the size of the array, to a length 1 shorter than before, thus clipping out the final value, which is no longer needed as it has been copied to the previous item in the array.

Finally, when the array upper bound has reached -1, there are no more items left in the array. In this situation we will Return a value of TRUE, which we will later use as a trigger to stop looking for more points.

Step 6 – Append points to polyline

The final stage of our changes to the drawing is to append points to our polyline in order of how close they are to the ends of our existing polyline. This works on a similar principle to the other subroutine – looping through the points looking for the nearest point, then adding the point to the polyline. This sub will add a single point to the polyline, and remove that point from the points() array.

Private Function AppendPoint(ByRef pl As Polyline, ByRef points() As DBPoint) As Boolean
Dim startPoint As Point2d = pl.StartPoint.Convert2d(New Plane)
Dim endPoint As Point2d = pl.EndPoint.Convert2d(New Plane)
Dim nearestPoint As String = ""
Dim shortestDist As Double = 1.0E+300 'A very very big number!
Dim remPoint As DBPoint

Dim n As Long
For n = 0 To points.GetUpperBound(0)

Dim targetPoint As Point2d
targetPoint = points(n).Position.Convert2d(New Plane)

Dim tmpDist As Double
tmpDist = startPoint.GetDistanceTo(targetPoint)
If tmpDist < shortestDist Then
shortestDist = tmpDist
nearestPoint = "startpoint"
remPoint = points(n)
End If

tmpDist = endPoint.GetDistanceTo(targetPoint)
If tmpDist < shortestDist Then
shortestDist = tmpDist
nearestPoint = "endpoint"
remPoint = points(n)
End If

Next

Select Case nearestPoint
Case "startpoint"
pl.AddVertexAt(0, remPoint.Position.Convert2d(New Plane), 0, 0, 0)
Case ("endpoint")
pl.AddVertexAt(pl.NumberOfVertices, remPoint.Position.Convert2d(New Plane), 0, 0, 0)
Case Else
Err.Raise(0, , "nearestPoint not set!")
End Select

Return RemovePoint(points, remPoint)

End Function

As noted earlier, RemovePoints will Return a TRUE value when there are no more points left in the array. This TRUE or FALSE signal is again passed back through this function, so that we are able to know if this was the last point added. See the Do – While loop, and the TimeToExit variable, in the code earlier on in this document.

Step 7 – Add the polyline to ModelSpace

The final subroutine is to simply add entities to ModelSpace, ensuring that we correctly add it to the transaction too:

Private Sub AddToModelSpace(ByVal db As Database, ByVal myT As Transaction, ByVal ent As Entity)

'Open the ModelSpace Block Table Record
Dim acBT As BlockTable = db.BlockTableId.GetObject(OpenMode.ForRead)
Dim BTR As BlockTableRecord
BTR = acBT(BlockTableRecord.ModelSpace).GetObject(OpenMode.ForWrite)

'Add the entity to the ModelSpace Block Table Record
BTR.AppendEntity(ent)

'Add the entity to the transaction
myT.AddNewlyCreatedDBObject(ent, True)

End Sub

Compiling The Project

If all has been coded correctly, you should now be able to save, and compile your project to a dll file! You can then use the NETLOAD command to load this dll into AutoCAD®, and invoke the command using whatever command name you specified before your main subroutine.

Join The Dots
Join The Dots

Source Files

I’ve included below a zip file containing all the source files for this project – just in case things went awry, you can hopefully find the problem. The command name I’ve used is JOINTHEDOTS.

jointhedots

Source Code

Also, below I’ve pasted ALL the source code for the project:

Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.Geometry
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.EditorInput
Imports Autodesk.AutoCAD.Colors

Public Class Class1

<CommandMethod("JoinTheDots")> _
Public Sub JoinTheDots()
'Setup
Dim ed As Editor = Application.DocumentManager.MdiActiveDocument.Editor

'Declare our filter entries this way
Dim values() As TypedValue = {
New TypedValue(DxfCode.Start, "POINT")
}

'Create the filter using our values
Dim sfilter As New SelectionFilter(values)

'Set the selection options
Dim SelOpts As New PromptSelectionOptions()
SelOpts.MessageForAdding = "Select points to find the shortest path through"
SelOpts.AllowDuplicates = True

'Make the selection
Dim res As PromptSelectionResult = ed.GetSelection(SelOpts, sfilter)

'If the user did something other than make a selection (like pressing ESC), then abort
If Not res.Status = PromptStatus.OK Then Return

'Create a selection set based on the user's selection
Dim ss As Autodesk.AutoCAD.EditorInput.SelectionSet = res.Value

'Create an array of object IDs from the selection set, so that we can loop through them easily
Dim idarray As ObjectId() = ss.GetObjectIds()

'Create a link to the active document's database
Dim db As Database = Application.DocumentManager.MdiActiveDocument.Database
'Create a transaction manager object
Dim tm As Autodesk.AutoCAD.DatabaseServices.TransactionManager = db.TransactionManager
'Start a transaction
Dim myT As Transaction = tm.StartTransaction()

'Create a coord array, the same size as the idarray
Dim points(idarray.GetUpperBound(0)) As DBPoint
'Populate the coord array with point2d objects representing the location of the DBPoint objects
Dim n As Long
For n = 0 To idarray.GetUpperBound(0)
points(n) = tm.GetObject(idarray(n), OpenMode.ForRead, True)
Next

'Find the shortest line formed by two coordinates, create a polyline representing this line, and
'remove the two coordinates from the coords array
Dim pl As Polyline = GetShortestLine(points)

Dim TimeToExit As Boolean = False
Do
TimeToExit = AppendPoint(pl, points)
Loop Until TimeToExit

'Add the polyline to modelspace
AddToModelSpace(db, myT, pl)

'Commit the transaction
myT.Commit()
'Dispose of our transaction
myT.Dispose()

End Sub

Private Function AppendPoint(ByRef pl As Polyline, ByRef points() As DBPoint) As Boolean
Dim startPoint As Point2d = pl.StartPoint.Convert2d(New Plane)
Dim endPoint As Point2d = pl.EndPoint.Convert2d(New Plane)
Dim nearestPoint As String = ""
Dim shortestDist As Double = 1.0E+300 'A very very big number!
Dim remPoint As DBPoint

Dim n As Long
For n = 0 To points.GetUpperBound(0)

Dim targetPoint As Point2d
targetPoint = points(n).Position.Convert2d(New Plane)

Dim tmpDist As Double
tmpDist = startPoint.GetDistanceTo(targetPoint)
If tmpDist < shortestDist Then
shortestDist = tmpDist
nearestPoint = "startpoint"
remPoint = points(n)
End If

tmpDist = endPoint.GetDistanceTo(targetPoint)
If tmpDist < shortestDist Then
shortestDist = tmpDist
nearestPoint = "endpoint"
remPoint = points(n)
End If

Next

Select Case nearestPoint
Case "startpoint"
pl.AddVertexAt(0, remPoint.Position.Convert2d(New Plane), 0, 0, 0)
Case ("endpoint")
pl.AddVertexAt(pl.NumberOfVertices, remPoint.Position.Convert2d(New Plane), 0, 0, 0)
Case Else
Err.Raise(0, , "nearestPoint not set!")
End Select

Return RemovePoint(points, remPoint)

End Function

Private Function GetShortestLine(ByRef points() As DBPoint) As Polyline

Dim n As Long
Dim m As Long

'Info that needs to be captured
Dim basePoint As DBPoint
Dim endPoint As DBPoint
Dim shortestDist As Double = 1.0E+300 'A very very big number!

'Loop through every combination of point pairs, and find the pair with the shortest distance
For n = 0 To points.GetUpperBound(0)
For m = n + 1 To points.GetUpperBound(0)

Dim tmpDist As Double
tmpDist = points(n).Position.DistanceTo(points(m).Position)

'If this is the shortest distance so far, update
If tmpDist < shortestDist Then
shortestDist = tmpDist
basePoint = points(n)
endPoint = points(m)
End If

Next
Next

'Add the points forming the shortest distance to a new polyline
Dim pl As Polyline = New Polyline
pl.AddVertexAt(0, basePoint.Position.Convert2d(New Plane), 0, 0, 0)
pl.AddVertexAt(1, endPoint.Position.Convert2d(New Plane), 0, 0, 0)

'remove basePoint and endPoint from the array of points, so that they are not reused
RemovePoint(points, basePoint)
RemovePoint(points, endPoint)

Return pl
End Function

Private Function RemovePoint(ByRef points() As DBPoint, ByRef remPoint As DBPoint) As Boolean
Dim n As Long
Dim newUpperBound As Long = points.GetUpperBound(0) - 1
Dim pointFound As Boolean
'Iterate through the points array until the removePoint is found, then nudge points down the array
For n = 0 To newUpperBound
If Not pointFound Then
If points(n) Is remPoint Then
pointFound = True
End If
End If
If pointFound Then
points(n) = points(n + 1)
End If
Next
'Set the new size of the array, clipping off the last item of the array
ReDim Preserve points(newUpperBound)

If newUpperBound = -1 Then
Return True
Else
Return False
End If

End Function

Private Sub AddToModelSpace(ByVal db As Database, ByVal myT As Transaction, ByVal ent As Entity)

'Open the ModelSpace Block Table Record
Dim acBT As BlockTable = db.BlockTableId.GetObject(OpenMode.ForRead)
Dim BTR As BlockTableRecord
BTR = acBT(BlockTableRecord.ModelSpace).GetObject(OpenMode.ForWrite)

'Add the entity to the ModelSpace Block Table Record
BTR.AppendEntity(ent)

'Add the entity to the transaction
myT.AddNewlyCreatedDBObject(ent, True)

End Sub

End Class

I hope this tutorial helped you get started with VB.NET in AutoCAD® – you’ll be developing your own tools in no time.

Also, don’t be disheartened if you find it difficult to get things going – its a learning curve, and you will get there. If you think I wrote all this code perfect first time, THINK AGAIN!!! It’s a process of trying things out, experimenting, and persisting.

Please subscribe to my blog if you found this helpful – my primary concern is giving great tips, tricks and tutorials. There is a lot more to come!

Regards,

Will

P.s. Seriously, subscribe!

VB.NET AutoCAD® Template

For those interested in AutoCAD® development, there are a few files that need to be referenced so that you can work with AutoCAD®. So, ideally, you’ll want to set up a basic template that you can use with all the basics set up ready for you. In this tutorial we will do just that.

I’m using visual Basic 2010 Express edition, but the process should be very similar for the latest versions of Visual Basic.

Firstly, create a new project. Select Class Library as your template. This type of file will compile to a .NET dll – just what we need for developing AutoCAD® tools.

Next, go to project properties, and then click on the references tab. There are two files you’ll need to add – AcMgd.dll, and AcDbMgd.dll. You can find these in your AutoCAD® directory – for example:

C:\Program Files\Autodesk\AutoCAD® Civil 3D® 2011

You may also have opted to download the ObjectARX libraries. If so, you can use the files located in here. Using these files allows you to develop for AutoCAD® without having to install AutoCAD® first. Whichever files you reference, ensure that the Copy Local property of both references is set to False. Because the files already ship with AutoCAD®, we do not want to be copying dll files all over the place as this can cause problems.

The next step requires you to save your project first, so do that. Once saved, go back to project properties and click on the Compile tab. Click on Advance Compile Options. Set the Target Framework to the version of the .NET framework that is suitable for the versions of AutoCAD® you are developing for. I have mine set to .NET framework 3.5, as I build my applications for AutoCAD® 2010 and above. Remember that .NET frameworks should be backward compatible, so if in doubt go for earlier versions rather than later versions, unless you have a specific reason not to do so.

We’re nearly there, but there is one last thing I like to do before saving as a template. Go back to your class, and we’re going to put in some default code, with some imports, and a subroutine with an associated command name that we will use when calling the command from the AutoCAD® command line:

Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.Geometry
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.EditorInput
Imports Autodesk.AutoCAD.Colors

Public Class Class1

<CommandMethod("COMMAND_NAME_HERE")> _
Public Sub COMMAND_NAME_HERE()

MsgBox("Hello World!")

End Sub

End Class

And that’s it! The final step is as simple as going File>Export Template, and following the wizard!

Hope this helps,

Will

P.s, sign up below to receive updates on my blog – don’t miss out on any tips like this!

Excel and AutoCAD® – A match made in heaven (again!)

Many people are oblivious to the wondrous things that can be achieved with programming. If you cringe at the prospect of writing code, I’ll put this to you now – I cringe at the thought of having to do things manually. Often (and yes, I mean often), I’ll write a little 6 line bit of code that saves me hours of work. Yes, HOURS – perhaps even days. Why people avoid learning this stuff is beyond me, because it really isn’t as hard as it looks.

Today I’m going to explain how you can write code in Microsoft Excel VBA that controls AutoCAD®. Firstly, let’s get VBA open in Microsoft Excel. With Excel open, press Alt+F11, which should open the VBA IDE (integrated development environment). If this doesn’t work, you can open this by going Tools>Macro>Visual Basic Editor. If you’re using Excel 2007+, you might struggle to find the option. You have to firstly go into Excel Options and check the box to show the Developer Tab on the ribbon interface.

So we’re now in a position to write a bit of code. On the left (or perhaps on your right depending on your PC), there should be a section called the Project Explorer. In here you should have a few things called Sheet1, Sheet2, Sheet3 and one called ThisWorkbook. Right click in this area and select Add Module. This will create an area for us to write our code, and if you’re feeling adventurous you can rename the module to whatever you like. Double click the module to edit it.

Now let’s see if we can get AutoCAD® to do something.

If you’ve done any programming before, you will know that you can have variables, and variables can have different types. These types can be simple, or can be more complex things known as objects. AutoCAD® has its own type library containing all the object types that we are likely to need. This is very useful to load into our application. To do this, go to Tools>References in the VBA window, and look for an option called AutoCAD® 2010 Type Library, or whatever version of AutoCAD® you are using. This has now made available some extra types that weren’t available before.

Now for some basic code! Put this code into the module, and press the run button at the top of the VBA editor. The subroutine name “Main” is unimportant – we could call this anything we like.

Sub Main()
    Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
    Set ACAD = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD
    ACAD.Visible = True 'Once loaded, set AutoCAD® to be visible
    ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
End Sub


Here we’ve created a new instance of AutoCAD®, and stored a handle to the AutoCAD® object (application) in the ACAD variable, then just printed a line to the AutoCAD® command line. Easy right? Ok, but we’re not going to want to open a new instance of AutoCAD® every time we want to run some code… So instead, we could use this, which links to an already open instance of AutoCAD:

Sub Main()
    Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
    Set ACAD = GetObject(, "AutoCAD.Application") 'Get a running instance of the class AutoCAD.Application
    ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
End Sub


Great – now we can link to a running instance of AutoCAD®. There is one last thing we need to do with this. If we run this code and AutoCAD® is not running, we will get an error message. Really, we ought to trap this exception – here’s one way this could be dealt with:

Sub Main()
    Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
    On Error Resume Next 'This tells VBA to ignore errors
    Set ACAD = GetObject(, "AutoCAD.Application") 'Get a running instance of the class AutoCAD.Application
    On Error GoTo 0 'This tells VBA to go back to NOT ignoring errors
    If ACAD Is Nothing Then 'Check to see if the above worked
        Set ACAD = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD
        ACAD.Visible = True 'Once loaded, set AutoCAD® to be visible
    End If
    ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
End Sub


This code firstly tries to link to an existing instance of AutoCAD®. We use the On Error Resume Next statement to skim over any errors that might occur when we try to link to an existing instance of AutoCAD®. It is very important that we also add the statement On Error Goto 0 after we’re done ignoring errors. At first glance you might think that it’s a good idea to skim over all errors by adding On Error Resume Next to the beginning of all our code, but this makes it much more difficult for us as developers to debug our application. Use of On Error Resume Next in excess is generally considered bad programming practice, but under controlled circumstances its use is no problem, and it helps trap our error in the example above.

After our call to the GetObject function, the ACAD variable either contains a link to our AutoCAD® object, or it contains “Nothing” as it was unable to locate one. In the latter case, we are going to create a new instance using the method explained in the first example.

Now we’re getting there.

Let’s actually do something useful now. Go to Excel – Sheet1, and fill columns A and B with some coordinates, X being in column A, and Y being in column B. Here is some data you can copy/paste if you like, though you may need to copy and paste the columns seperately:

3
7
5
2
3
4
5
6
7
8
8
8
5
3
1.6
1
1
1
1.6
3

 

In Excel we can access the data in a worksheet by using Sheet1.Cells(Row, Column). We can loop through Sheet1.Cells and take action in AutoCAD® based on the content of the cells. Below is a quick example of how this can be achieved. The loop that is used is known as a For-Next loop, which increments the value of n in this example from 1 to 10. Then we’re just taking the data from the cells at row n, and using the data to insert a point into AutoCAD®. If you used the data above you’ll end up with a nice smiley face drawn in points!

Sub Main()
    Dim ACAD As AcadApplication 'Create ACAD variable of type AcadApplication
    On Error Resume Next 'This tells VBA to ignore errors
    Set ACAD = GetObject(, "AutoCAD.Application") 'Get a running instance of the class AutoCAD.Application
    On Error GoTo 0 'This tells VBA to go back to NOT ignoring errors
    If ACAD Is Nothing Then 'Check to see if the above worked
        Set ACAD = New AcadApplication 'Set the ACAD variable to equal a new instance of AutoCAD
        ACAD.Visible = True 'Once loaded, set AutoCAD® to be visible
    End If
    ACAD.ActiveDocument.Utility.Prompt "Hello from Excel!" 'Print a message to the AutoCAD® command line
    Dim Coords(2) As Double 'This is an array of double precision floating point numbers
    ' The array goes from 0 - 2, which will contain our coordinates X, Y and Z
    Dim n As Integer 'Create the variable n as the type Integer
    For n = 1 To 10 'Loop this code, incrementing the value of n from 1 to 10
        Coords(0) = Sheet1.Cells(n, 1) 'Put the Column 1 value into the Coords array
        Coords(1) = Sheet1.Cells(n, 2) 'Put the Column 2 value into the Coords array
        ACAD.ActiveDocument.ModelSpace.AddPoint Coords 'Add a point in AutoCAD® at this location
    Next
End Sub


So there we have it – an introduction to using VBA in Excel to control AutoCAD®. Obviously what we have done here only scratches the surface of the capabilities, but I’ll leave you to get creative with the that… for now at least.

As with all my posts I’d finally like to encourage you to subscribe to my blog. I’m always going to be adding new content on here, and I’ll always try to explain everything the best I can. Also, I’ll always be willing to help you with any specific problems that you have, so please do sign up and get involved on my site.

Will

Break a line into smaller pieces using VBA or VB.NET in AutoCAD

Here’s a simple example of some VBA code that might come in handy either as a learning exercise, or if you happen to be trying to break a line programatically.

The code fistly asks the user to select a line, and the object is stored in the Line variable. Then, I’ve hard-coded the NumberOfSegments variable to equal 5. Next, we calculate what the “offset” would be for each line if we were to divide the original line up into 5 segments. Using this value, we then set the position of the existing line to be the length of the first line in the new set of lines. Then, using the offset calculated earlier, we can copy the line, and move by the amount defined in the Offset variable.

Option Explicit

Sub ExplodeLine()
    Dim NumberOfSegments As Long
    Dim Line As AcadLine
    Dim NewEndPoint(2) As Double
    Dim BasePoint(2) As Double
    Dim Offset(2) As Double
    Dim n As Long
    Dim p As Variant
    
    ThisDrawing.Utility.GetEntity Line, p, "Pick a Line..."
    NumberOfSegments = 5
    Offset(0) = (Line.EndPoint(0) - Line.StartPoint(0)) / NumberOfSegments
    Offset(1) = (Line.EndPoint(1) - Line.StartPoint(1)) / NumberOfSegments
    NewEndPoint(0) = Line.StartPoint(0) + Offset(0)
    NewEndPoint(1) = Line.StartPoint(1) + Offset(1)
    Line.EndPoint = NewEndPoint
    
    For n = 2 To NumberOfSegments
        ' Loop (NumberOfSegments - 1) times as the first already exists
        Set Line = Line.Copy
        Line.Move BasePoint, Offset
    Next
    
End Sub

Regards,
Will

MText.WidthFactor

If you’ve ever tried to edit the widthfactor of mtext through VBA or VB.NET, you’ll have realised that there isn’t a method for doing so. However, there is a built in trick which bypasses the requirement for doing this. Try the code below:

Sub main()
    Dim p As Variant
    Dim mt As AcadMText
    ThisDrawing.Utility.GetEntity mt, p, "Pick an MTEXT object..."
    mt.TextString = "\W0.5;" & a.TextString
End Sub

Preceeding the TextString property with the prefix \W0.5; tells AutoCAD® to make all the text have a width factor of 0.5. You can also edit the width factor of individual parts of the TextString, by surrounding the text you want to change in curly brackets, as shown below.

Sub main()
    Dim p As Variant
    Dim mt As AcadMText
    ThisDrawing.Utility.GetEntity mt, p, "Pick an MTEXT object..."
    mt.TextString = "{\W0.5;narrow} {\W2;wide} {\W0.5;narrow} {\W2;wide} {\W0.5;narrow} {\W2;wide}"
End Sub

Hope this helps – if it did, please do subscribe to my blog. I’ll be uploading many more tips and tricks regularly.

ThisDrawing.PaperSpace

ThisDrawing.PaperSpace is a very useful way to access the PaperSpace of your drawing through VBA or VB.NET.

When developing tools that draw entites in a drawing, we can sometimes use ThisDrawing.PaperSpace, forgetting that the tool might actually end up being used in ModelSpace. This would result in bahaviour that is not expected by the user. The ideal solution would be if there were an ActiveSpace method of the ThisDrawing object, but unfortunately this does not exist. There is a workaround however:

Function ThisSpace() As AcadBlock
    If ThisDrawing.ActiveSpace = acModelSpace Then
        Set ThisSpace = ThisDrawing.ModelSpace
    Else
        Set ThisSpace = ThisDrawing.PaperSpace
    End If
End Function

Use this function to return the block object of either ModelSpace or PaperSpace – whichever is actively open by the user. This solves the problem mentioned above, ensuring that you are always writing code that edits the space that is currently being worked on by the user. Use a call to this function in the place of ThisDrawing.PaperSpace.

I have many tutorials on my site for how to use your VBA code in VB.NET projects. I also explain what you need to get started with coding in VB.NET, and where to download the required software for free.