Vector Class Tweaks

I have been working on Vector class VBA code to draw Autocad lines as vectors. The first version separated 2D and 3D vectors into two different classes. One reason to do this is the vector angle is figured differently. Another is I wanted to use a 2D or a 3D arrow head. Many math books, analytic geometry or calculus, introduce them in two different chapters. The goal is to make VBA vector algebra notation as similar as possible to math notation. Or at least readable. Now I have combined the classes, just ignoring any difficulty, to eliminate duplicated code, while i use and tweak. I also removed the addition and scalar multiplication from the class module to make the parameter list complete and not a function of one of the vectors (tho for mult this was not necessary, it will be useful for dot product). A work in progress. I will post code when i am satisfied with it.


3D Vector Angle

The angle of a 3D vector is the angle from the vector directly to each of the 3 positive axes. The angles are named alpha (x-axis), beta(y-axis) and gamma(z-axis). They are always positive and between 0 and 180 inclusive. They are called direction angles.

The arrowhead is inserted at rotation angle 0 at the endpoint of the vector then rotated. 2D rotation rotates around a point that is actually an axis normal (perpendicular) to the current UCS. The easiest way to rotate the arrowhead into position is to make a UCS that includes the plane of the alpha (or beta or gamma) angle between the vector and the axis. if the vector does not have a startpoint at the origin, a line parallel to the axis at the startpoint of the vector is used. after the ucs is made, the arrowhead is inserted and rotated by the alpha angle. the same procedure works for the other axes and direction angles.

how can the arrowhead be moved into position with only one rotation? If the vector is located by two angles, the third angle can be calculated. Imagine standing up a vector and dimensioning two angles, the other angle is fixed. the first rotation is the rotation of the ucs, the second angle is the alpha and final rotation needed.

The VBA UCS method uses 3 points, a new origin, a point on the postive new x-axis and a point on the positive new y-axis. Its very easy to work with but it required 3 points that form a right angle. Draw a line from the end of the vector perpendicular to the axis. that is the projection of the vector on the axis and the new origin point on the axis. another point any distance in the direction of the positive axis is the second point. The new y-axis point is the endpoint of the vector.

 '3D Vectors
     Set blockrefObj = acadDoc.ModelSpace.InsertBlock(endpt2, blkname, 0.375, 0.375, 0.375, 0)
     Call set_ucs(px2, py1, pz1, _
                  px2 + 1, py1, pz1, _
                  px2, py2, pz2, _
         blockrefObj.Rotate endpt2, alpha
      'these are just for reference
       Call set_ucs(px1, py2, pz1, _
                  px1, py2 + 1, pz1, _
                  px2, py2, pz2, _

       Call set_ucs(px1, py1, pz2, _
                  px1, py1, pz2 + 1, _
                  px2, py2, pz2, _

Sub set_ucs(x1 As Double, y1 As Double, z1 As Double, _
            x2 As Double, y2 As Double, z2 As Double, _
            x3 As Double, y3 As Double, z3 As Double, strname As String)
   'pt1 is origin, pt2 is xaxis, pt3 is yaxis
    Dim ucsObj As AcadUCS
    Dim originPt(0 To 2) As Double
    Dim xAxisPt(0 To 2) As Double
    Dim yAxisPt(0 To 2) As Double
   originPt(0) = x1: originPt(1) = y1: originPt(2) = z1
   xAxisPt(0) = x2: xAxisPt(1) = y2: xAxisPt(2) = z2
   yAxisPt(0) = x3: yAxisPt(1) = y3: yAxisPt(2) = z3

   Set ucsObj = acadDoc.UserCoordinateSystems.Add(originPt, xAxisPt, yAxisPt, strname)
    acadDoc.ActiveUCS = ucsObj

 End Sub

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"

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"

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.

Autocad Point Variable

All of Autocad graphics methods use a 3 place array of doubles for the coordinates.

The simplest way to sub this is by passing the static array for the sub to fill data.

Dim PtA(0 To 2) As Double
Call pt1(ptA, 1, 2, 0)

Sub pt1(ByRef pnt() As Double, x As Double, y As Double, z As Double)
pnt(0) = x: pnt(1) = y: pnt(2) = z
End Sub

This changes ptA in the calling program. Another way is to make a function and pass the array back to a receiving variable.
This requires a dynamic array.

Dim ptA() As Double
ptA = Pt(1, 2, 0)

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

We can even get away with this – no variables at all.

Set lineAB = acadDoc.ModelSpace.AddLine(Pt(1, 4, 0), Pt(9, 1, 0))

Dynamic arrays can accept point values. A lot of objects return point values, autocad help always seems to use a single variant to hold the array.

The utility polarpoint method returns a point value.

RetVal = object.PolarPoint(Point, Angle, Distance)
Point Type: Variant (three-element array of doubles)
Return Value Type: Variant (three-element array of doubles)

Dim polarPnt As Variant
Dim basePnt(0 To 2) As Double

polarPnt = ThisDrawing.Utility.PolarPoint(basePnt, angle, distance)
Set lineObj = ThisDrawing.ModelSpace.AddLine(basePnt, polarPnt)

PolarPoint returns an array. You cannot assign to a static array. Dynamic arrays can assign. If the declaration is to a dynamic array with the correct type Double it still works (in my version.)

Dim polarPnt() As Double

A Table is an Array

Autocad tables and VBA arrays have the same structure. You can make a sub procedure that takes an array passed as argument that makes an autocad table. The table sub can read the array and determine how many rows and columns it contains. The array is made in any sub specific to the task and separate from making or loading the table. The program flow can make just the data table without Title or Headers and add those later from other data.

The simplest way to make an array is with the array function.

ar_labels = Array(“MKNO”, “QTY”, “LENGTH”, “WIDTH”, “DESC”)
‘ ar_labels is single dimension 0 to cnt – 1

Debug.Print LBound(ar_labels) ‘get 0
Debug.Print UBound(ar_labels) ‘get 4

The autocad method to Addtable requires 5 parameters.

RetVal = object.AddTable(InsertionPoint, NumRows, NumColumns, RowHeight, ColWidth

Rowheight and colwidth is up to you. To keep it simple use what generic table Standard supplies at first. numrows and numcolumns come from looking at the array upper and lower index.

To make a table display a single dimension array in a single row.

Call make_1D_table(ar_labels)

Sub make_1D_table(ar As Variant)
' ar is single dimension 0 to cnt - 1
' tbl is public as AcadTable
' RowHeight and ColWidth are public as double
' location pt0 would be public too as soon as needed

     Dim pt0(0 To 2) As Double '000
     Dim i As Integer, j As Integer
     Dim rowcount As Integer, colcount As Integer
    rowcount = 1
    colcount = UBound(ar) - LBound(ar) + 1
    'create the table sized for the array
    Set tbl = acadDoc.ModelSpace.AddTable(pt0, rowcount, colcount, RowHeight, ColWidth)
      'object.UnmergeCells minRow, maxRow, minCol, maxCol
    tbl.UnmergeCells 0, 0, 0, 0
    tbl.TitleSuppressed = True
     tbl.HeaderSuppressed = True
 'right here is where table format has to occur before data is entered

'zero base array fits with autocad zero base table
 For j = 0 To colcount - 1
  If Not IsEmpty(ar(j)) And (ar(j)) <> "" Then
     tbl.SetText 0, j, ar(j)
  End If
 Next j
End Sub

For our main 2 dimensional data table, we do the same thing but get table dims first. One issue that comes up on adding tables is the behavior of title and header rows. Another issue is when text overflows a single line and causes the row width to pop down. It pops down automatically, but not up. The cell width should be set before the data is loaded. This table sub is set up to only make data rows. The way it works though, the table is made with title and header rows, I dont think there is any way to stop that, and then the table object methods are used to modify the table. You might want to make the textsize of the title row the same as data in the table style manager, if you are using the Standard style. Otherwise depending on the data loaded, you may get a top row with a different height.

After we get the table made, in real life we want to have our own tablestyle and probably do some formatting of the text before it is written to screen. I am just showing the data side here.

Public ar_labels As Variant
Public ar_dims As Variant
Public tbl As AcadTable
Public RowHeight As Double
Public ColWidth As Double
Public hexstart As String

Sub make_2D_table(ar As Variant)
'table is two-dimensional and any-base
' ar(rows,columns)
'  tbl is public As AcadTable
'  RowHeight and ColWidth are public as Double
'  pt0 could be public when needed
    Dim i As Integer, j As Integer
    Dim rowcount As Integer, colcount As Integer
    Dim rowLbound As Integer, colLbound As Integer
    Dim rowUbound As Integer, colUbound As Integer
    Dim pt0(0 To 2) As Double
    rowLbound = LBound(ar, 1)
    rowUbound = UBound(ar, 1)
    colLbound = LBound(ar, 2)
    colUbound = UBound(ar, 2)
    rowcount = rowUbound - rowLbound + 1
    colcount = colUbound - colLbound + 1
    Set tbl = acadDoc.ModelSpace.AddTable(pt0, rowcount, colcount, RowHeight, ColWidth)
    'the tablestyle does not dictate the use of a title or header
    'at this point the table has a title and header
    'whether they are merged on creation is per style method EnableMergeAll "Title", True
    'if the title row textsize in standard is larger than data textsize
    'the title row cell height may be larger than data rows.
   '     data rows only option
     tbl.UnmergeCells 0, 0, 0, 0
     tbl.TitleSuppressed = True
     tbl.HeaderSuppressed = True

 'right here is where table format has to occur before data is entered
 'using the methods of tbl object we could hand off to a sub here
       For i = rowLbound To rowUbound
         For j = colLbound To colUbound
             If Not IsEmpty(ar(i, j)) Then
         tbl.SetText i - rowLbound, j - colLbound, ar(i, j)
             End If
         Next j
       Next i
 'a sub to add title or header can run next
 'tbl.InsertRows 0, RowHeight, 1
End Sub

Here is a sub to make a multiplication table array with 12X12 hard wired in.
You can experiment with different numbers and see if the table sub handles it.
There is no title or header row.

Sub test_mult_tbl()
'only job is to fill array ar_dims global
 Dim rows As Integer, i As Integer
 Dim columns As Integer, j As Integer
    rows = 12
    columns = 12
    ReDim ar_dims(1 To rows, 1 To columns)
    For i = 1 To rows
       For j = 1 To columns
           ar_dims(i, j) = i * j
       Next j
    Next i
End Sub

Sub test_226()
    Call Connect_Acad
    Call test_mult_tbl
        RowHeight = 0.125
        ColWidth = 0.625
    Call make_2D_table(ar_dims)
End Sub

You can make a font table using ascii codes. Fonts use hex codes which are base 16. A 16X16 table displays 256 characters. After we make the data table we will add a title row and put the name of the font in it.

Sub test_ascii_table()
  ' only job is to make array
  ' 0 to 255 ascii table 16^2
Dim rows As Integer, i As Integer
Dim columns As Integer, j As Integer
    rows = 16
    columns = 16
    ReDim ar_dims(1 To rows, 1 To columns)
    For i = 1 To rows
        For j = 1 To columns
            'ar_dims(i, j) = CInt(((i - 1) * 16 + (j - 1)))
            ar_dims(i, j) = Chr(((i - 1) * 16 + (j - 1)))
        Next j
    Next i

End Sub

It gets called as before but we are adding a title row after the data is written.
Tablestyles have textstyles, so I am creating a new tablestyle each time using the current font name, and putting that font style name into the tablestyle to be used.

Sub test_228()
Call Connect_Acad

'call style before table call
    Call mk_tbl_styl(acadDoc.GetVariable("textstyle"))

'makes ar_dims
    Call test_ascii_table

    RowHeight = 0.125
    ColWidth = 0.375

    Call make_2D_table(ar_dims)

 'add a title row to top after plain table made
   tbl.InsertRows 0, RowHeight, 1
   tbl.MergeCells 0, 0, 0, tbl.columns - 1
   tbl.TitleSuppressed = False
   tbl.SetText 0, 0, acadDoc.GetVariable("textstyle")
End Sub

Unicode is a long extension of ascii. There are many sections. You have to look up the hex code of the section you want to display.

Sub test_unicode()
'only job is to make array of unicode block numbers
'hexstart public string

 Dim numstart As Double
 Dim rows As Integer, i As Integer
 Dim columns As Integer, j As Integer
    rows = 16
    columns = 16
    ReDim ar_dims(1 To rows, 1 To columns)
    numstart = HexToDec(hexstart)
    For i = 1 To rows
        For j = 1 To columns
            ar_dims(i, j) = DecToHex(numstart + (i - 1) * 16 + (j - 1))
            ar_dims(i, j) = "\U+" & ar_dims(i, j)
        Next j
    Next i
End Sub

Sub test_229()
Call Connect_Acad
Call new_textstyle("Cambria Math", "Cambria Math")

hexstart = "2200"
Call test_unicode
   RowHeight = 0.125
   ColWidth = 0.5

Call make_2D_table(ar_dims)
   'add title row with caption hexnum and textstyle name
   tbl.InsertRows 0, RowHeight, 1
   tbl.MergeCells 0, 0, 0, tbl.columns - 1
   tbl.TitleSuppressed = False
   tbl.SetText 0, 0, "&H" &  hexstart & " " & acadDoc.GetVariable("textstyle")
End Sub

Header rows can be inserted just like Title rows. The header data can come from the Array command. The sub is similar to the 1D sub but even simpler.