Strings as Symbols

If we can interpret strings as symbols, we can store parameter data in spreadsheets.

The basic technique uses VBA statements Replace and Evaluate.

Sub test()
Dim A As Double, B As Double, C As Double, D As Double, R As Double

Dim str As String

str = "A + B * C + D"

A = 5
B = 3
C = 2
D = 3

str = Replace(str, "A", A)
str = Replace(str, "B", B)
str = Replace(str, "C", C)
str = Replace(str, "D", D)

R = Evaluate(str)

MsgBox R

End Sub

Lets use a simple polyline box to illustrate the all-in-code method versus the data-in-spreadsheet method.

If the box is A wide (in the x direction) and B tall (in the y direction), and the lower left corner is at 0,0, the points are (0,0) (A,0) (A,B) (0,B)

AddLightWeightPolyline will draw the box if the 8 data entries are given in an array in sequence. The CLOSED property of the polyline object is set to true to draw the line from the last point back to the first point.

In code
X0=0
X1=A
Y0=0
Y1=B

Dim pts as variant
Pts = Array (x0, y0, x1, y0, x1, y1, x0, y1)

The array named pts is then handed off to a sub that will convert it to a format AddLightWeightPolyline can handle.

For any complex shape a labeled drawing is necessary. Creating the array is a two-step process. x and y values are found starting from the origin in relation to the parameters A and B (and any others necessary). Then the x and y values are listed as needed in the array in the order that the polyline vertices require. At runtime the x and y values have their formulas evaluated and the results are stored in the array given to the polyline sub to be drawn.

To duplicate this with the data in a spreadsheet, the process has to be collapsed to a single step. We need to store the formulas in the order the polyline requires them, not evaluate them to x and y symbols first.

At first the added complexity of that was tedious. But eventually I learned to enter the formulas per the sketch just doing all the x values, in the order they are to be drawn, then do all the y values, similar to the code process. The benefits of putting the data into a spreadsheet are that we can have a whole sheet of parts, and we can manipulate the data and the finished part easily.

In standard database design, every table has a unique name with one column that has unique values called a primary key. The record (row) is found by finding the unique value in the key column. If we call the spreadsheet table SHAPE then the unique column will be called SHAPE_ID. We find the row data by the name of the shape we are looking for. For instance, the key column is column B, the shape we are looking for is “OSCF”, then

Set rng = ws1.Range(”B1:B30”).Find(”OSCF”)

Find has arguments. If the lookat:=xlWhole is not set, Find will search and find the substring, so that searching for OSCF will stop when OSCF1 is found. Also it is written that VBA saves its last search parameters, and uses them when there are no arguments to the contrary, which could lead to some pretty confounding bugs.

Set rng = ws1.Range(”B1:B30”).Find(”OSCF” , LookIn:=xlValues, lookat:=xlWhole)

in practice variables will be used for the range and search string

Set rng = ws1.Range(shape_key).Find(shape_ID, LookIn:=xlValues, lookat:=xlWhole)

If found, this will set the excel range object to the single cell that contains the found string.

If our data is extended out to the right, and there is a blank column after the last cell, then

First we move the range one cell to the right to pick up the first data cell

Set rng = rng.Offset(0, 1)

Then we extend the range all the way to the right, a variable number of columns depending on the individual record.

Set rng = ws1.Range(rng.Address, rng.End(xlToRight).Address)

Ws1 is a sheet reference.

Now we have the data, whatever it is, in a range object. In the cells are our formulas. Here are the values for OSCF,

A, B, and W are defined by the user at run time. But the strings A, B and W in the spreadsheet are not the symbols A, B and W in VBA.

The range is saved. We count the number of items in it and re-dimension the array to accept it.

icount = rng.Count
ReDim ar(1 To icount)

Now we can loop through the range. Each time through the loop we get the cell value in a string. Then we use VBA Replace to change the string values A, B, W to their symbols which at runtime have actual numerical values. Finally we use VBA Evaluate to do the math and load the result into the array. The finished array is an array of doubles and suitable for the AddLightWeightPollyLine method.


Sub shape_2(shape_ID As String, A As Double, B As Double, C As Double, D As Double, W As Double)
 Dim i As Integer, icount As Integer
 Dim str As String
 Dim rng As Range
 Dim plineobj As AcadLWPolyline
  
 Dim ar() As Double
 Dim shape_key As String
 
 Set ws1 = ThisWorkbook.Worksheets("Shape_Param")
 shape_key = "B1:B30"
 Set rng = ws1.Range(shape_key).Find(shape_ID, LookIn:=xlValues, lookat:=xlWhole)

 
 If rng Is Nothing Then
   MsgBox "no find shape_ID in column shape_key"
    Exit Sub
    End If
   
    'rng has one cell,  offset it one cell right to begin data
    Set rng = rng.Offset(0, 1)
    'extend the range to right to the end of the record
     Set rng = ws1.Range(rng.Address, rng.End(xlToRight).Address)
     'this also works but it seems like it shouldnt
     'because excel seems to infer the range default as address
     'Set rng = Range(rng, rng.End(xlToRight))
        icount = rng.Count
        ReDim ar(1 To icount)
    
    For i = 1 To icount
        str = rng.Cells(1, i)
        str = Replace(str, "A", A)
        str = Replace(str, "B", B)
        str = Replace(str, "C", C)
        str = Replace(str, "D", D)
        str = Replace(str, "W", W)
        
        ar(i) = Evaluate(str)
    Next i

  Set plineobj = acadDoc.ModelSpace.AddLightWeightPolyline(ar)
      plineobj.Closed = True
      plineobj.Update
      Set g_pline = plineobj

End Sub

The created polyline can be a global variable and the calling program can draw several shapes and move, rotate, mirror them into assemblies. For drawing sheet metal end sections, either the part can be drawn with a thickness, a closed polyline, or a single not-closed polyline. Thats the origin of my having two subs Shape_1 and Shape_2. They differ only by whether they close the polyline at the end. I preload 4 variables A,B,C,D, and W which I use for thickness, but if they are not needed, zeros can be passed.

Since this is a spreadsheet, not an actual database, our records can have a variable number of columns, we can skip lines, we can have sections of closed and not closed parts. The only requirement is that the key column contains the name of the part.

Different parts drawn with shape_ID and parameters.

Sub test2_sheet()
    Call init_draw
    Dim A As Double, B As Double, C As Double, D As Double, W As Double
    Dim shape_ID As String
    
    A = 2
    B = 4.25
    C = 0
    D = 0
    W = 0.0625
    
    shape_ID = "OSCF"
    
    ' shape_ID = "ISCF"
    ' shape_ID = "CAP"
    ' shape_ID = "FLOOR"
    'shape_ID = "FLAT"
    'shape_ID = "JCHAN"
    'shape_ID = "HANG"
     
    Call shape_2(shape_ID, A, B, C, D, W)
    
    pt1 = pt(4, 4, 0)
    g_pline.Move pt0, pt1
    
End Sub

Assemblies drawn using global polyline methods move, rotate, mirror


Sub test1_sheet()
    Call init_draw
 
    Call shape_2("box", 34, 0.0625, 0, 0, 0)
    
    Call shape_2("box", 34, 0.0625, 0, 0, 0)
    g_pline.Move pt0, pt(0, 3.9375, 0)
    
     Call shape_2("box", 1, 3.875, 0, 0, 0)
     g_pline.Move pt0, pt(0, 0.0625, 0)
    
    Call shape_2("box", 1, 3.875, 0, 0, 0)
     g_pline.Move pt0, pt(33, 0.0625, 0)
     
  acadApp.Update
End Sub

More complex assemblies can use a selection set to block the result using parameters in the name. So its pretty easy to develop a lot of similar parts with different dimensions.

Sub part_end_view_2(W As Double, Thk As Double)
 
    Dim strblk As String
    strblk = "Panel " & Thk & " x " & W - 1 & " GL"
     
    Call init_draw
    Dim sset As AcadSelectionSet
    addss "SSBLOCK"
    Set sset = acadDoc.SelectionSets.Item("SSBLOCK")
 
    Call shape_1("FM_SINGLE", W, 0, 0, 0, 0)
    sset.Select acSelectionSetLast

    g_pline.Mirror pt(0, Thk / 2, 0), pt(5, Thk / 2, 0)
    sset.Select acSelectionSetLast
  
    Call shape_1("CHAN_SINGLE", 1, Thk - 0.125, 0, 0, 0)
    g_pline.Move pt0, pt(0, -(Thk - 0.125) / 2, 0)
    g_pline.Rotate pt0, PI
    g_pline.Move pt0, pt(1.25, Thk / 2, 0)
    sset.Select acSelectionSetLast
  
    Call shape_1("CHAN_SINGLE", 1, Thk - 0.5, 0, 0, 0)
    g_pline.Move pt0, pt(0, (-(Thk - 0.5) / 2), 0)
    g_pline.Move pt0, pt(W - 1.25, Thk / 2, 0)
    sset.Select acSelectionSetLast
     
    make_blk sset, strblk
    sset.Erase
    sset.Clear
    sset.Delete
    acadDoc.ModelSpace.InsertBlock pt0, strblk, 1, 1, 1, 0
  
    acadApp.Update
End Sub

When rotating and moving, sometimes its conceptually easier to go backwards. What point is easiest to reference in the final position? Move the part so that point is at 0,0 then rotate about the origin and move from there. Or you can draw the object in the rotation and position you wish by experimenting with the point values in the spreadsheet.

I have found the Evaluate function in VBA is pretty robust and it doesnt matter whether all the spreadsheet entries have the proper spaces, A+W or A + W both are evaluated correctly.

EDIT:- a bug,

the code ran many times before this error popped up. When it does error, it seems to always be that Evaluate is trying to convert a string representing an integer to a double. Other integers work fine, 6 instead of a 4, input from a form, exact same code, CDBL does not seem to help. Variant does not help. something here i am not getting.

When errors make no sense, i tell people, re-boot.

the downside to sheet driven parts – besides sometimes it does not run – its conceptually simpler to see it in code. parameters in a sheet are more fragile, its much easier to delete data in a sheet than code. protect the sheet if you give it out.

on the other hand, I quickly made several assembly drawing programs using sheet driven parts.

this seems to get past the error, though it needs further looking at.

Dim dbl As Double

For i = 1 To icount
str = rng.Cells(1, i)
str = Replace(str, “A”, A)
str = Replace(str, “B”, B)
str = Replace(str, “C”, C)
str = Replace(str, “D”, D)
str = Replace(str, “W”, W)

On Error Resume Next
dbl = CDbl(Evaluate(str))

If Err Then
ar(i) = CDbl(str)
Err.Clear
Else
ar(i) = Evaluate(str)
End If

On Error GoTo 0

Next i

Approximating the Circle

Drawing Circles the Hard Way – with Straight Lines

Our turtle has a local viewpoint. He can draw a line one unit, turn one degree, then repeat that 360 times, coming back around where he started, but at no time is a center or radius known, even though the approximate circle has both. By measuring the drawn approximate circle or by doing a little math the radius can be found. The circumference is total direction traveled. Using the formula Circum = pi*(Dia) and substituting 360 for the Circum the radius is found to be 180 / pi or approx 57.3.

If we make the subroutine more general to accept as input the angle turned between each line and the length of the lines, we no longer have a loop of 360 and we need to calculate the number of lines to draw.

num_lines = 360 / angle

will give a full circle (as long as angle is a multiple of 360). With this sub we can experiment with varying angles and line lengths and see how the radius changes. Using 1 and 1 gives the same results as before, but also using any two numbers that are the same, such as 10 and 10, give a circle (more or less) with the same radius as 1 and 1. Using different numbers for angle and line length will make the circle diameter change as a direct proportion of the ratio

len_lines / ang.

Longer lines will give larger diameters. Larger angles will give smaller diameters.

We can see by experimentation that every ratio of line_length to angle has a definite radius, so lets find that equation.
We already needed an equation between num_lines and ang, which was num_lines = 360 / ang. If for instance we turned 120 degrees with each turn, we would only need 3 lines and our approximate circle would be a triangle. If we turn one degree, we need 360 lines.

We also used the fact that 360 lines of one unit had a circumference of 360. No matter how many lines of whatever length,
the circumference is num_lines * len_lines.

C= (num_lines) * (len_lines) and into that we substitute our calculation num_lines = 360 / ang.

C = (360 / ang) * (len_lines)

Circumference of course is 2 pi R
2 pi R = (360/ang) * len_lines
R = (180/ang) * (len_lines/pi)

R = (180/pi) * (len_lines/ang)

and there is our ratio of line length to ang as a direct proportion to R.

Don’t forget, like I did when measuring the radius of a polygon, this radius is calculated by adding the straight line lengths and calculating the radius of a circle of that circumference. If the straight line approximation is crude, the radius will be crude. The more lines used to approximate the circle, the better the radius calculated from them.

R and ang can be switched with a little algebra to find ang.

ang = (180 / pi) * ( len_lines / R)

and now we can re-write our sub-routine so it accepts the radius and len_lines as argument and calculates the angle to turn each line and the number of lines to close (or almost close) the circle.

Finally having written a general program to draw circles of a given radius using straight lines of a given length, drawing an arc of given degree is just reducing the number of lines drawn by the same ratio as arc degrees to 360.

for a circle
num_lines = 360 / ang

for an arc with deg as the new input
num_lines = 360 / ang
num_lines = (deg / 360) * num_lines

but more simply this is
num_lines = deg / ang

Turtle Basic 2019

Turtle Basic 2019

A very useful, advanced, early book is “Turtle Geometry” by Harold Abelson and Andrea diSessa, two MIT scientists, published in 1980. The MIT group had been working 10 years or more at that time with Turtle geometry, Logo and Lisp. The book is written with emphasis on the mathematical ideas, not any specific implementation. The ideas are just as valid now as then. We can use their substantial, challenging concepts and implement them 40 years later. Our examples can go beyond what they show, because our tools are so much better.

I am doing a turtle graphics implementation using Autocad, creating a turtle class in excel VBA. Excel is simply providing the VBA editor. The principles and code would would work just as well in dot net, and identically in vba native in autocad or bricscad.

Position and Heading are the two basic turtle properties. Heading will be in degrees, between 0 and 360, not including 360. VBA and autocad demand radians. Our subs will do the conversion. Position consists of variables X and Y (and Z when the turtle sprouts wings some day). We will use type Double for all.

Class variables are either Private or Public. If a variable is Public it can be set directly. That should do for X and Y. If Heading is public, then Turtle.Heading = 361 is possible. We want to convert values to between 0 and 359.99. Get and Let manage Private class variables. These can be named anything you want but they cannot have the same name as the variable they control.

Basic turtle commands are FORWARD #, BACK #, RIGHT # and LEFT #. These are methods or procedures that change Position or Heading properties. PENUP and PENDOWN change a boolean PEN variable.

In a Class Module, not a standard code module –

Public x1 As Double
Public y1 As Double
Public x2 As Double
Public y2 As Double
Private pheading As Double
Public pen As Boolean

Current Position is x1, y1. The other endpoint of the line the turtle is going to draw is x2, y2. The heading is private. All others are public.

Insert Procedure Property from the VBA pulldown will insert a stub procedure to get a start on controlling a private variable. These normally have the same name. You would use the same name to read and write, which is how every property works. But lets use Heading for the read property and SetHeading for the write property. So instead of something like

Turtle1.heading = turtle1.heading + 45

We have

Turtle1.setheading = turtle1.heading + 45

In the class module is the Let, the Get, and the convertang function. The only way to set the Heading is thru Let which converts every angle to a value between 0 and 360, no matter how many consecutive turns or negative values added.

Public Property Get heading() As Double
heading = pheading
End Property

Public Property Let setheading(ByVal ang As Double)
pheading = convertang(ang)
End Property

wordpress is really hard to deal with, it thinks these inequality signs are html tags

The basic line drawing function is FORWARD #. Position and Heading are known. The only value required is distance. The other end of the line, x2, y2, has to be calculated with Cos and Sin, which require radians, not degrees. The value of the Pen boolean is checked to see if the line is to be drawn. The line is drawn with normal autocad vba methods. Finally the endpoint x2,y2 is made the new current position.

Public Sub forward(dist As Double)
'assumes x1 y1 and heading
x2 = x1 + dist * Cos(ang2rad(pheading))
y2 = y1 + dist * Sin(ang2rad(pheading))

If pen Then
Call drawline(x1, y1, x2, y2)
End If

'updates to new position
x1 = x2
y1 = y2
End Sub

 Sub drawline(x1 As Double, y1 As Double, x2 As Double, y2 As Double)
'internal sub to draw line
Dim acadline As acadline
Dim pt1(0 To 2) As Double
Dim pt2(0 To 2) As Double
pt1(0) = x1: pt1(1) = y1: pt1(2) = 0
pt2(0) = x2: pt2(1) = y2: pt2(2) = 0

Set acadline = acadDoc.ModelSpace.AddLine(pt1, pt2)

Update
End Sub

Since this is autocad, or something very much like it, we could definitely have turtle properties for line width, color and type. But we will save those for later.

Back is the same as Forward, except we add 180 to the direction, but we do not change the Heading variable.

x2 = x1 + dist * Cos(ang2rad(pheading + 180))
y2 = y1 + dist * Sin(ang2rad(pheading + 180))

Changing Heading with Left # and Right #

Public Sub left(ang As Double)
setheading = pheading + ang
End Sub

Public Sub right(ang As Double)
setheading = pheading - ang
End Sub

The degree to radian utility and Penup / Pendown

Function ang2rad(ang As Double) As Double
ang2rad = ang * Pi / 180
End Function

Public Sub penup()
pen = False
End Sub

Public Sub pendown()
pen = True
End Sub

In a standard code module, the class has to be instantiated, that means a new specific turtle object has to be created using the class template. If CTurtle is the name of the class module, then –

Dim turtle1 As CTurtle
Set turtle1 = New CTurtle

The variables are set with default value zero, so that debug.print turtle1.x1 would print 0. In the class module you can set initial values.

Private Sub Class_Initialize()
pen = True
pheading = 90 'traditional turtle direction
End Sub

To begin drawing, lets start with a basic polygon. An interior angle of an equilateral triangle is 60 degrees. The exterior angle is 120 degrees. The exterior angle is the angle you would turn if you were walking the lines of the triangle. Its the continuation of the line you are on past the vertex onto the next line. Its “how much the turtle must turn in drawing the vertex” (p.7 – Abelson).

Sub turtle_triangle()
connect_acad
Dim i As Integer
Dim turtle As CTurtle
Set turtle = New CTurtle
turtle.setheading = 60

For i = 1 To 3
turtle.fd 10
turtle.right 120
Next i

End Sub

In practice to save a little typing, I will do some of the declarations in public and subs.

Sub turtle_triangle()
init_turtle
turtle1.setheading = 60

For i = 1 To 3
turtle1.fd 10
turtle1.right 120
Next i

End Sub

To generalize a polygon, the total exterior angles sum up to 360 – the turtle makes one full turn to come back to its initial heading. The simplest polygon, or N-gon where N stands for number of sides, would have one degree turns and have 360 sides.

 Sub turtle_polygon(num_sides As Integer, angle As Double, len_side As Double)
init_turtle

For i = 1 To num_sides
turtle1.fd len_side
turtle1.right angle
Next i

End Sub

This has to be called by something with arguments. You have to know what the arguments are to get good regular polygons. I am sticking with double as type for angle, not integer. Num_sides has to be integer, because a half side is not realistic, and also num_sides is used as a counter in a for loop. A double actually would run there without error, but sooner or later you would miss your expected result by one item due to a rounding error.

Here is a demo which makes a variety of polygons.

Sub polygon_demo()
turtle_polygon 3, 120, 1
turtle_polygon 4, 90, 2
turtle_polygon 5, 72, 3
turtle_polygon 6, 60, 4
turtle_polygon 7, (360 / 7), 5
turtle_polygon 8, 45, 6
turtle_polygon 9, 40, 7
turtle_polygon 10, 36, 8
turtle_polygon 11, (360 / 11), 9
turtle_polygon 12, 30, 10
End Sub

Given the number of sides, and given the fact that the exterior angles always add up to 360, the turn angle is just 360 / num_sides. In the case of 7 and 11 sides, the angle is not an integer. Its a repeating decimal. I let vba calculate the number and feed whatever precision it wants to autocad, and it closes the polygon fine.

Since the angle is calculated we could put that into the sub and take it out of the arguments list. We could do it the other way, calculate the number of sides from the angle, but thats trickier because num_sides is an integer and we might not always get an integer from a division.

So we can calculate angle, take it out of the argument list, and get exactly the same results.

Sub turtle_polygon2(num_sides As Integer, len_side As Double)
init_turtle
Dim angle As Double
angle = 360 / num_sides

For i = 1 To num_sides
turtle1.fd len_side
turtle1.right angle
Next i
End Sub

But what about this idea of knowing the angle and not knowing the number of sides? The polygon is done when the turtle turns exactly 360 degrees. If the angle is a double though, some angles are not multiples of 360. If we are not going to control the loop with the number of sides as a counter, we need a way to stop when the turtle returns to its original heading and an emergency stop in case it never does. Using doubles for heading, there is no guarantee it will ever exactly be 360 degrees once it starts, due to double rounding imprecision.

Here is a Do Loop where the test is at the end of the loop, so heading starts out zero, or whatever, it adds one increment, then it checks before running the loop again. In addition I have an emergency counter to stay out of an infinite loop. The parameters are length of the side and angle. No opinion expressed about how many sides there will be. In practice it turns out and is logical, if the angle is an integer, the maximum number of sides will be 360.

Angle 45 should give us an octagon, and it does, with 8 lines.

Sub do_poly2()
connect_acad
Set turtle1 = New CTurtle
poly_demo2 1, 45
End Sub

90 gives a square, 120 a triangle, 36 gives a 10-gon. What if I try to draw a 7-gon? First lets let VBA do the math.

poly_demo2 1, (360 / 7)

Looks like it works fine, but when I list all the lines, I get 201 (or whatever my max counter is). They are on top of one another, I dont see any separation, I dont see any difference in the listing, 8 decimal places, but there is a difference out there somewhere. It looks like a septagon. It appeared to work before because we were controlling the number of sides, and here we are not.

We knew there would be non-closing figures. Any angle, integer or not, that is not a multiple of 360 is not going to give a closed polygon. For any angle that is a multiple of 360 we get a simple convex polygon. Some angles are not multiple of 360 but a multiple of 360 times an integer. For instance, 108 * 10 = 360 * 3. If we input 108 the figure goes all the way around 3 times before the heading is exactly zero again, and it draws a total of 10 lines.

poly_demo2 1, 108

More Turtle Graphics

A basic class implementation for turtle graphics in autocad –

The basic idea of turtle graphics is that the pen has a location and a direction. The instruction to draw a line only needs distance. The ending point is the new current location. To translate distance at angle from a given point to coordinates the Sin and Cosine are used.

The public class variables are x1, y1 – the current location, the beginning of the line to be drawn, and x2, y2, the calculated end points. Heading is a private double. It is private so that the class can always keep the angle heading between 0 <= heading < 360 no matter how many cumulative turns. A boolean PEN variable allows a PENUP or PENDOWN state.

Turtle1.FD 6 draws a line 6 units (assuming PEN is DOWN). Turtle.Left 45 and Turtle.Right 45 turn heading to the left or right 45 degrees or any number. Input to the user is in degrees. The class module converts to radians in private.

some example code using the turtle class –

Sub turtle_demo_A()
connect_acad

Dim turtle1 As CTurtle
Set turtle1 = New CTurtle

Debug.Print turtle1.x1
Debug.Print turtle1.y1
Debug.Print turtle1.pen
'x1 and y1 are zero
'pen is true
'these are class defaults

Debug.Print turtle1.heading
'access to private variable pheading is thru LET and GET HEADING
'class_initialize default is 90

turtle1.heading = 540
Debug.Print turtle1.heading
'property Let heading (double)
'seems like an argument but you call LET with assignment
'property let heading sets and controls value between 0 <= pheading < 360
'heading is 180

turtle1.heading = turtle1.heading + 180
Debug.Print turtle1.heading
'heading is 0
'just like A = A + 3
'right side of equation is GET and left side is LET

turtle1.heading = turtle1.heading - 45
Debug.Print turtle1.heading
'heading is 315

turtle1.left 90
Debug.Print turtle1.heading
'heading is 45

turtle1.right 90
Debug.Print turtle1.heading
'heading is 315

turtle1.heading = turtle1.heading + 180
Debug.Print turtle1.heading
'heading is 135

turtle1.fd 12
'line is 45 to left

End Sub

all this boils down to –


Sub turtle_demo_B()
connect_acad

Dim turtle1 As CTurtle
Set turtle1 = New CTurtle

turtle1.heading = 45
turtle1.x1 = 2
turtle1.y1 = 3

turtle1.fd 12
End Sub

The Class Module code for the turtle to draw a line contains the trigonometry to calculate the point at dist and angle. It draws the line using the familiar AddLine method with EndPoints as an array of 3 doubles, xyz. This is a 2D implementation, Z is always zero for now but does not have to be.

Public Sub fd(dist As Double)
'assumes x1 y1 and heading
x2 = x1 + dist * Cos(ang2rad(pheading))
y2 = y1 + dist * Sin(ang2rad(pheading))

If pen Then
Call drawline(x1, y1, x2, y2)
End If

'updates to new position
x1 = x2
y1 = y2
End Sub

Sub drawline(x1 As Double, y1 As Double, x2 As Double, y2 As Double)
'internal sub to draw line
Dim acadline As acadline
Dim pt1(0 To 2) As Double
Dim pt2(0 To 2) As Double
pt1(0) = x1: pt1(1) = y1: pt1(2) = 0
pt2(0) = x2: pt2(1) = y2: pt2(2) = 0

Set acadline = acadDoc.ModelSpace.AddLine(pt1, pt2)
Update
End Sub

Drawing the same line in code with no class implementation –

Sub turtle_demo_C()
connect_acad

Dim acadline As acadline
Dim pt1(0 To 2) As Double
Dim pt2(0 To 2) As Double

Dim x1 As Double, y1 As Double
Dim x2 As Double, y2 As Double

Dim ang As Double
Dim dist As Double

x1 = 2
y1 = 3
ang = 45
dist = 12

x2 = x1 + dist * Cos(ang2rad(ang))
y2 = y1 + dist * Sin(ang2rad(ang))

pt1(0) = x1: pt1(1) = y1: pt1(2) = 0
pt2(0) = x2: pt2(1) = y2: pt2(2) = 0

Set acadline = acadDoc.ModelSpace.AddLine(pt1, pt2)
acadApp.Update
End Sub

Instead of doing the calculations, Autocad provides the Utility PolarPoint to do the trig. Polarpoint returns an array. Autodesk help uses a Variant to capture it, but a dynamic array works fine (see pt2).

Sub turtle_demo_D()
connect_acad

Dim acadline As acadline
Dim pt1(0 To 2) As Double
Dim pt2() As Double

Dim x1 As Double, y1 As Double

Dim ang As Double
Dim dist As Double

x1 = 0
y1 = 0
ang = 45
dist = 12

'these are commented out
'x2 = x1 + dist * Cos(ang2rad(ang))
'y2 = y1 + dist * Sin(ang2rad(ang))

pt1(0) = x1: pt1(1) = y1: pt1(2) = 0
pt2 = acadDoc.Utility.PolarPoint(pt1, ang2rad(ang), dist)

Set acadline = acadDoc.ModelSpace.AddLine(pt1, pt2)
acadApp.Update
End Sub

We can further simplify this process with a function to populate point arrays. Every Point can be declared as a dynamic array.

Function Pt(x As Double, y As Double, z As Double) As Double()
Dim pnt(0 To 2) As Double
pnt(0) = x: pnt(1) = y: pnt(2) = z
Pt = pnt
End Function

Sub turtle_demo_E()
connect_acad

Dim acadline As acadline
Dim pt1() As Double
Dim pt2() As Double

Dim ang As Double
Dim dist As Double

ang = 45
dist = 12

pt1 = Pt(2, 3, 0)
pt2 = acadDoc.Utility.PolarPoint(pt1, ang2rad(ang), dist)

Set acadline = acadDoc.ModelSpace.AddLine(pt1, pt2)
acadApp.Update
End Sub

we can streamline a little bit more with a dedicated Line sub-routine. now lets compare the turtle and more conventional autocad methods. Each will draw a line and turn before drawing the next. Using dynamic arrays, what was pt2 can become pt1 with a simple assignment. That is not possible with the conventional static array where points are declared as – Dim PT1 (0 to 2) as Double.

Sub turtle_demo_F()
connect_acad

Dim turtle1 As CTurtle
Set turtle1 = New CTurtle

turtle1.heading = 30
turtle1.x1 = 1
turtle1.y1 = 2

turtle1.fd 12
turtle1.left 30
turtle1.fd 12

Dim pt1() As Double
Dim pt2() As Double

Dim ang As Double
Dim dist As Double

ang = 45
dist = 12

pt1 = Pt(1, 2, 0)
pt2 = acadDoc.Utility.PolarPoint(pt1, ang2rad(ang), dist)
line1 pt1, pt2

pt1 = pt2
pt2 = acadDoc.Utility.PolarPoint(pt1, ang2rad(ang + 30), dist)
line1 pt1, pt2

acadApp.Update
End Sub

Turtle graphics has geometry implications, start here, go forward, turn and repeat. Turtle graphics is local with a simple interface and limited command set. Coordinate graphics is a global grid, but its interface can also be simplified. The two approaches might be able to work together.

A random star generator –

Sub turtle_demo_6()
init_turtle
Dim dblsize As Double
Dim inc As Integer

For inc = 1 To 480

dblsize = rnddbl(0, 360)
turtle1.heading = dblsize

dblsize = rnddbl(0, 1024)
turtle1.x1 = dblsize

dblsize = rnddbl(512, 1024)
turtle1.y1 = dblsize

dblsize = rnddbl(2, 17)
star_5 dblsize

Next inc

End Sub

Sub star_5(dblsize As Double)

For i = 1 To 5
turtle1.fd dblsize
turtle1.right 144
Next i

End Sub

Function rnddbl(upr As Double, lwr As Double) As Double
' Randomize
' better results without Randomize

rnddbl = CDbl((upr - lwr + 1) * Rnd + lwr)
End Function

any comment in the code causes wordpress to substitute the html equivalent, even the code tag vb with quotations gets corrupted. use wordpress code tag and it moves by itself above an empty line. I really struggle sometimes with wordpress and its code behavior. The only way i even get it to work is to load the old editor. There is an easier way to edit posts, they helpfully remind me. I tried that a few times.

3D Vector Class

Two vectors can be added. Three vectors can be added. Three vectors at right angles on the axes can be resolved as components of any 3D vector.


Sub test_3d_vector3()
Call connect_acad

Dim vs As C3DVector
Dim vt As C3DVector
Dim vu As C3DVector
Dim vv As C3DVector

Set vs = New C3DVector
vs.pts_xyz 0, 0, 0, 3, 0, 0

Set vt = New C3DVector
vt.pts_xyz 0, 0, 0, 0, 4, 0

Set vu = New C3DVector
vu.pts_xyz 0, 0, 0, 0, 0, 5

vs.draw "s"
vt.draw "t"
vu.draw "u"

Set vv = v3D_3_add(vs, vt, vu)
vv.draw "s + t + u"

acadApp.Update
End Sub


Sub test_3d_vector5()
Call connect_acad

Dim i As C3DVector
Dim j As C3DVector
Dim k As C3DVector

Set i = New C3DVector
i.pts_xyz 0, 0, 0, 1, 0, 0

Set j = New C3DVector
j.pts_xyz 0, 0, 0, 0, 1, 0

Set k = New C3DVector
k.pts_xyz 0, 0, 0, 0, 0, 1

i.draw "i"
j.draw "j"
k.draw "k"

Dim rx As C3DVector
Dim ry As C3DVector
Dim rz As C3DVector

Set rx = v3D_scalar(3, i)
Set ry = v3D_scalar(4, j)
Set rz = v3D_scalar(5, k)

Dim resultant As C3DVector
Set resultant = v3D_3_add(rx, ry, rz)

rx.draw "rx"
ry.draw "ry"
rz.draw "rz"
resultant.draw "resultant"

acadApp.Update
End Sub

Vector Class in Autocad VBA

Vectors have length, direction and angle. In engineering and science, vectors can be moved tip to tail to add forces and create a resultant vector. Vectors are equal if magnitude and direction are equal. Position is arbitrary. 2D vectors can fully describe with one (x,y) pair. When the vector starts at (0,0), the end point is also the delta x and delta y.

The autocad line already has everything it needs to be a vector. The direction is saved in separate variables for start and end point. The acadline object in VBA has all the properties required of a vector – StartPoint, EndPoint, Length, Angle and Delta. Delta is the vector. Delta is returned as a 3 place array of doubles, exactly the same as StartPoint and EndPoint, but it’s not a point, it’s (x2-x1, y2-y1, z2-z1). We save it to a variable as if it were a point. We use it to do vector algebra – the algebra of lines.

An object vector is given a variable name, such as U, V, W, S or T, usually lower case and bold, and specified to be equal to the delta values.

angle brackets (this wordpress is html and it will not allow angle brackets for any purpose other than the one it has in its mind) are used to show (x,y) (imagine angle brackets) is not the same thing as (x,y).

Vectors are added by adding their delta values. if u = (ux,uy) and t = (tx,ty) then u + t = (ux+tx, uy+ty). Vectors can also be subtracted and scaled. The angle and length they make can be calculated from the delta. Vectors of different length and angle are easily added to form a new vector with new length and new direction.

A great deal of engineering mechanics and physics vector work can be done just by drawing lines of appropriate length and direction and moving the vectors tip to tail, measuring the resultants.

The parallelogram rule states that if two vectors are to be added, draw them as adjacent sides of a parellogram, the diagonal is the sum. If 3 or more vectors to be added, they are moved one after the other and the resultant is start point to finish.

The math of adding, subtracting and scaling vectors is simple. Creating a vector class in VBA allows the formation, properties and rules of calculations to be formalized. This is a first simple draft.

Vectors in different locations with the same length and direction are declared equal. Math is done on vectors regardless of position. If a vector start point is at 0,0, that is declared to be standard position. In order to physically draw the vector in autocad, we have to have a position. So we may want to specify vectors assuming the start point is 0,0 with length and angle parameters. Or we may want to specify with a single point value as the endpoint. Other vectors we may want to specify the start point and parameters. That gives us 5 possible ways to specify a vector. The first two assume 0,0 as the start point. Using (x1,y1) as start point, and (x2,y2) as endpoint –

vector1 (x2,y2)
vector2 (Length, Theta)
vector3 (x1,y1, x2,y2)
vector4 (x1,y1, Length, Theta)
vector5 (x1,y1,x_delta, y_delta)

In VBA classes, the variables used may be hidden from the user, while the names of property subs are the interface. We use the good names for properties and reference names for the variables. We want (i think) to save all required data even though it is redundant. The angle and length can be calculated from the point values, and vice versa, so they have to be consistent.

property names – variables
3 place array of doubles
pt1 – startpt1
pt2 – endpt2
delta – pdelta

simple doubles
angle – pangle
length – plength
delta_x – pdelta_x
delta_y – pdelta_y
x1 – px1
x2 – px2
y1 – py1
y2 – py2

Properties are implemented with Get (return of value from variable) and Let (assignment of value to variable) statements. The easiest way to start them is to use the VBA editor pulldown under Insert Procedure and click Property. It will add each. We dont really need Let statements yet in this first implementation. Variables are assigned when the vector is first initialized in a single sub procedure. (I am going to post screenshots while this is still in a state of flux.)

The angle of the vector can be calculated from Tangent of delta y over delta x, but tangent has a period of 180 degrees and vectors rotate from 0 to 360, not including 360, so i wrote a simple program to test in each quadrant.

When the vector is specified with length and angle, the initialization sub can be shortened, so it is not redundant. (SLA here stands for Start, Length, Angle)

The vector.draw method –
This arrow is not integral. It is a 1-unit long block inserted at the end point of the line at a scale that looks good using the angle of the vector. The vector line is full length of course, so on-screen calculations work. The arrow can be erased. A switch could be added in a more polished program to arrow or not arrow. The optional parameter adds a text label at the midpoint of the vector.

This is all we need to get started with vectors. The calculation programs are external to the class.

Here is a test demo and the autocad output.

The math is simple, but we will not be able to use VBA symbols “+ – *” for vector addition, subtraction and multiplication. Those are reserved. Subtraction is accomplished by using a -1 scalar factor and adding the negative vector. Functions return a vector object. We need to set up a vector variable to receive the result.

another interesting application of the parallelogram rule is that one diagonal is the sum, the other is the difference.