au09 cp318-1 inventor api intro assemblies

61
Introduction to Autodesk® Inventor® API and Assemblies Wayne Brill – Autodesk CP318-1 This session will introduce you to the Inventor API with a particular emphasis on Assemblies. Topics covered will include how to control the placement of components in an assembly using a 3D matrix and how proxy objects are used to represent components in the assembly space. You will also see how "Level of Detail" is supported programmatically. VB.NET and VBA will be used to demonstrate the power of the API. About the Speaker: Wayne has been a member of Autodesk Developer Technical services supporting ADN (Autodesk Developer Network) for nine years. Currently, Wayne provides API support for AutoCAD, Autodesk Inventor®, AutoCAD® Mechanical, AutoCAD OEM, and RealDWG™. [email protected]

Upload: aviosopaula

Post on 09-Sep-2014

206 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and AssembliesWayne Brill – Autodesk

CP318-1 This session will introduce you to the Inventor API with a particular emphasis on Assemblies. Topics covered will include how to control the placement of components in an assembly using a 3D matrix and how proxy objects are used to represent components in the assembly space. You will also see how "Level of Detail" is supported programmatically. VB.NET and VBA will be used to demonstrate the power of the API.

About the Speaker:Wayne has been a member of Autodesk Developer Technical services supporting ADN (Autodesk Developer Network) for nine years. Currently, Wayne provides API support for AutoCAD, Autodesk Inventor®, AutoCAD® Mechanical, AutoCAD OEM, and RealDWG™.

[email protected]

Page 2: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

IntroductionLearning how to customize Inventor can be fun. A large Application Programming Interface (API) like this, with a lot of details to understand can also be challenging. I see this in my role as a support engineer for ADN (Autodesk Developer Network) where I often have the opportunity to help developers who are just starting with the Inventor API.

In this session I will help you quickly get up to speed with Inventor customization by focusing on the API objects for automating assemblies. I believe that if you are going to be automating Inventor you will probably want to know at least the basics of using the API for assemblies. After you gain a basic understanding you can branch out and master other areas of the API as well.

This document is intended to be a supplement to the power point slide and examples used during the session and will be a resource after the class. There are four main sections. The first two are intended to be an introduction to the API. The last sections are detailed discussions on Vectors, Matrices and the B-Rep API that you can use to gain a better understanding of these more complex objects.

Overview of the API and VBA API for Assemblies . Vectors, Matrices B-Rep API

Note: This is not a beginner’s class on programming. I do review simple concepts of using a COM API. However this class may get too complicated if you do not have some experience with COM programming. Also the discussion will make a lot more sense if you already know the basics of using Inventor to create assemblies.

Overview of the Inventor API and VBAIf you take a look at the Inventor API object model you will see that many of the objects in the Inventor API are organized to follow the main document types in Inventor. (Parts, Assemblies, Drawings). Other sections in the API are used to create user interfaces and other objects that are not related to a specific document type. You can download a PDF that contains a diagram of the Inventor API Object Model from this URL- http://www.autodesk.com/developinventor (You will find other resources available for the Inventor API as well)

2

Page 3: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

The Object Model PDF is also available from the Inventor SDK. (Software Development Kit) The SDK will be in a directory similar to this:

C:\Program Files\Autodesk\Inventor 2010\SDK\DeveloperTools\Docs

The SDK ships with Inventor however separate msi files need to be run to install it. These are DeveloperTools.msi and UserTools.msi. The location of the installer is different for Windows XP and Windows Vista or Windows 7.

Windows XP: C:\Program Files\Autodesk\Inventor 2010\SDK\DeveloperTools.msi

Windows Vista or 7: C:\Users\Public\Documents\Autodesk\Inventor 2010\SDK\DeveloperTools.msi

For more information on the SDK see this file:

C:\Program Files\Autodesk\Inventor 2010\SDK\SDK_Readme.htm

You can use any language that supports COM automation such as Visual Basic, VB.NET, C# and C++ to automate Inventor. You will probably find that the easiest way to get started with the Inventor API is to use Visual Basic for Applications (VBA) which is included with Inventor (The examples in this handout are VBA examples). You can open the VBA editor from the Tools tab as seen in the following screenshot. (or Alt+F11)

3

Page 4: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

VBA ExampleIf you are new to COM programming you may not be aware that API objects are available through a type library. In the VBA Editor you can see the referenced libraries by going to Tools>References. The Autodesk Inventor Object Library (RxInventor.tlb) is automatically referenced in the Inventor VBA editor so you can start using the API without adding other references.

Now let’s go ahead and add a procedure and do some simple things with the Inventor API. Copy and paste the code below to the VBA editor. When this VBA procedure is run a variable named invApp is instantiated as an Object of the Inventor.Application type. In VBA (and VB6) use the Dim and Set keywords to instantiate objects (In VB.NET you do not use the Set statement). Once the object is instantiated you can use properties and methods of the object to access Inventor. Notice that ThisApplication is used to return the Inventor Application.

4

Page 5: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

ThisApplication is a short cut to the Application object (The ThisApplication shortcut is only available by default like this in VBA).

Public Sub Demo01_ChangeCaption() ' Instantiate an Inventor Application variable Dim invApp As Inventor.Application Set invApp = ThisApplication 'Get the Inventor Window Caption Dim strCaption As String strCaption = invApp.Caption ' Print the caption in the immediate window Debug.Print strCaption ' Change the Caption invApp.Caption = "Custom Caption" End Sub

In this example the Caption of the Inventor Application is printed to the immediate window using Debug.Print. The immediate window is one of the Windows in the VBA editor (use Cntrl+G to display it). Using Debug.Print is one way to get feedback about what is happening when your code is run. A String variable is used to store the value of the caption. The Caption property of the Inventor Application object is also used to change the Inventor Application caption to “Custom Caption” (The caption property is read/write). This screen shot was taken after I ran the procedure twice. You can see what the caption was the first and second time the code was run.

5

Page 6: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Using the Object BrowserThe VBA Object Browser provides a way to explore the objects in the Inventor API. You can display the Object Browser from the VBA View Menu (View>Object Browser or F2). You can select a library to search and a string to search on. In the screen shot below shows the Inventor Library is selected and the search is for Application. The selected class is Application. The selected member is the ActiveDocument property.

6

Page 7: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

In Object Oriented programming, a class is a type and an object is an instantiation of that type. In the Object Browser you see classes and the properties and methods these classes have (I have been using the word “object” for both classes and objects).

Dim and Set statementsDiscussing the Dim and Set statements will help you understand what the Object Browser shows. In VBA programming the Dim statement declares the object of the type and the Set statement instantiates it. The code snippet below declares a variable of the type Inventor.Application and sets it to the Inventor.Application returned by the ThisApplication short cut.

Dim invApp As Inventor.ApplicationSet invApp = ThisApplication

This is one of the foundations to understanding how to program with a COM API like this. You declare a class and then instantiate it so that it is a (live) object. Once you have the object you can drive Inventor by changing the properties of the object or calling one if it’s methods. In the Object Browser shown above the ActiveDocument is selected. In the comments for this property

7

Page 8: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

it states that it will return a Document (Property ActiveDocument as Document). The document is instantiated by using the ActiveDocument property. After the document variable is instantiated you can call methods and properties on it. In the snippet below the ActiveDocument is retrieved and the full file name of the document is printed in the immediate window.

Dim oDoc As DocumentSet oDoc = invApp.ActiveDocumentDebug.Print oDoc.FullFileName

In this screenshot you can see the Intellisense for a Document object. Intellisense is very helpful when you can’t quite remember the method or property you need.

Methods, Properties and ParametersI have been talking about objects. I need to also make it clear what I mean by Methods and Properties. A method is something that an object can do. An example of this would be the Quit method of the Application object (I bet you can guess what this does). A property is a quality of an object. The Application.Caption property is an example. Notice that a dot is used to access the methods or properties of an object. Parameters are values needed for the method or property. In the screen shot below the Parameters are FullDocumentName and an optional parameter OpenVisible. The intellisense for the parameters appear after typing the open parenthesis.

Debugging in VBAVBA supports debugging. One way to debug is to use the Watches window. In the screen shot below the Watches window is showing values of the Inventor.Application properties. A break point was added on the line of code that sets the string to the Inventor Caption. In the watches

8

Page 9: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

window you can see the current value of this setting (when the break point was hit). This is the value that will be assigned to the String variable strCaption.

You can add a variable to the watch window by right clicking on it and selecting “Add Watch”. You can add a break point to a line of code by placing the cursor on the line and hitting F9. You can also simply click in the bar on the left side of the code window.

Collections Objects in the APIMany of the classes in the Inventor API are collections. A collection as it implies is a grouping of similar objects. In the snippet below the oDocs variable is declared as a type Documents and instantiated with the Documents property of the Inventor.Application. The number of open documents is printed to the immediate window by calling the Count property of the Documents variable.

Dim oDocs As DocumentsSet oDocs = invApp.DocumentsDebug.Print "Number of open documents = " & oDocs.Count

You can iterate through the collection using a for next loop as in this snippet. When this code is run the full file name of each document will be printed in the immediate window.

Dim oDoc As DocumentFor Each oDoc In oDocs Debug.Print oDoc.FullFileNameNext oDoc

9

Page 10: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Collections are one based Before we dive into a discussion about the objects for assemblies we need to mention a couple of things. The Inventor API is one based. This means that collections do not have a zero element and the first element in a collection will be returned using 1(one), (Application.Documents.Item(1)). This may be different from other COM APIs you have used.

UnitsAnother thing you will want to remember is that Inventor uses internal units for different types of measure. In the user interface this conversion to the internal unit from the current displayed unit is done automatically. When you are using methods or properties that take a number you need to be aware that the unit used may be different from what you are expecting. Here are the internal units.

10

Page 11: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

If the user provides a number in a unit that is different than the default unit then you will need to convert it to get the correct behavior. The UnitsOfMeasure property of the document object is used to create a UnitsOfMeasure object. This object is used to easily facilitate the conversion between one unit and another.

In the following screenshot you can see a double is created with the value of 1. If you used this value you may not get the results you expect. Is this one inch or one centimeter for example? I can convert it to the value needed using the UnitsOfMeasure object. In this example it is converted from inches to centimeters and then from centimeters to inches.

ParametersParameters are important to most work flows when using Inventor. The Inventor API supports parameters in an assembly in the Parameters collection of the AssemblyComponentDefinition. You can access parameters to get and set their values and use them in your code.

11

Page 12: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

The example below prints the names and values of all of the parameters in the immediate window. This example also shows that you can use the Type property to determine if the parameter is a model, table or user parameter.

Public Sub iterateParameters() If ThisApplication.ActiveDocument.DocumentType <> kAssemblyDocumentObject Then Exit Sub Dim oAsmDoc As AssemblyDocument Set oAsmDoc = ThisApplication.ActiveDocument Dim oAsmCompDef As AssemblyComponentDefinition Set oAsmCompDef = oAsmDoc.ComponentDefinition Dim oParam As Parameter For Each oParam In oAsmCompDef.Parameters Debug.Print oParam.Name Select Case oParam.Type Case kModelParameterObject Debug.Print " Type: " & "Model Parameter" Debug.Print "Value = " & oParam.Expression Case kTableParameterObject Debug.Print " Type: " & "Table Parameter" Debug.Print "Vale = " & oParam.Value Case kUserParameterObject Debug.Print " Type: " & "User Parameter" Debug.Print "Vale = " & oParam.Value End Select Next oParamEnd Sub

Here is a screenshot showing the parameters listed in the immediate window.

12

Page 13: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

API for Assemblies

AssemblyDocumentNow that you have an idea about how to access the Inventor API let’s focus on the API for assemblies. The AssemblyDocument object is the top level object.

You can use the Add method of the Documents collection to create a new AssemblyDocument. In the following example a new AssemblyDocument is created and another AssemblyDocument is opened. If you call the save method it will create an .iam file (hope this isn’t too obvious).

In the Add method, (used to create a new document) notice that the first parameter is kAssemblyDocumentObject (parameters are separated by commas). This parameter specifies that an assembly document will be created. The second parameter specifies a template and the third parameter (Boolean true) will make the AssemblyDocument visible. The Open method takes a string for the path and name of the AssemblyDocument to open.

Public Sub Demo_NewAndOpenAssembly() ' Create a new Assembly Document Dim oAsmDoc As AssemblyDocument

13

Page 14: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Set oAsmDoc = ThisApplication.Documents.Add _ (kAssemblyDocumentObject, _ ThisApplication.FileManager.GetTemplateFile(kAssemblyDocumentObject), True)

Dim oAsmDoc2 As AssemblyDocument Set oAsmDoc2 = ThisApplication.Documents.Open _ ("C:\Autodesk University\AU 2009\Assembly1.iam")End Sub

The AssemblyDocument object allows you to control things such as the settings that pertain to assembly documents. In the following example a couple of settings for the active assembly are set. UnitsOfMeasure LengthUnits is changed to inches and LengthDisplayPrecision is changed to four decimal places. The grid settings for sketching are also changed using the MinorLinesPerMajorGridLine property of the assembly document SketchSettings property.

Public Sub Demo_Assembly_Doc_Settings() ' Instantiate an Assembly Document variable Dim oAsmDoc As AssemblyDocument Set oAsmDoc = ThisApplication.ActiveDocument ' Change the LengthUnits to inch oAsmDoc.UnitsOfMeasure.LengthUnits = kInchLengthUnits ' Change the LengthDisplayPrecision to 4 oAsmDoc.UnitsOfMeasure.LengthDisplayPrecision = 4 ' Change the setting for MinorLinesPerMajorGridLine oAsmDoc.SketchSettings.MinorLinesPerMajorGridLine = 8 End Sub

Here is a screen shot of the intellisense for an AssemblyDocument.

14

Page 15: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

The following screenshot shows the results of running the previous example. Notice the major grid lines are displayed every eight grid lines and the units are set to inch. You can see how easy it is to change settings using the API (A lot better than using the UI if you had to change something like this for lots of iam files).

15

Page 16: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

AssemblyComponentDefinitionSome of the properties for the AssemblyDocument return another object. The ComponentDefinition is one such property. This property of an AssmeblyDocument returns an AssemblyComponentDefinition.

Just to be clear, each AssemblyDocument will have its own AssemblyComponentDefinition. Here is a procedure that gets an AssemblyComponentDefinition from a AssemblyDocument object and prints out the number of occurrences. Notice that the ComponentOccurrences property of an AssemblyComponentDefinition object will return the ComponentOccurrences collection.

Public Sub Demo_Assembly_CompDef() ' Instantiate an Assembly Document variable Dim oAsmDoc As AssemblyDocument Set oAsmDoc = ThisApplication.ActiveDocument Dim oAsmCompDef As AssemblyComponentDefinition Set oAsmCompDef = oAsmDoc.ComponentDefinition Dim oCompOccs As ComponentOccurrences Set oCompOccs = oAsmCompDef.Occurrences Debug.Print "Number of occurences in the Active Assembly = " & oCompOccs.Count End Sub

.

16

Page 17: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Here is the result of running the code example above. Notice how we get the ComponentOccurrences from the AssemblyComponentDefintion (ComponentDefinition property) and use Debug.Print with the Count property of the ComponentOccurences object.

ComponentOccurrencesYou use one of the Add methods of the ComponentOccurences object to add components to the assembly. In the following screenshot you can see the intellisense for the Add method. Notice that the first parameter is a string that is the path of the document name. This would be an .ipt or an .iam file. (an iam file would be a sub assembly). The second parameter is a Matrix which is used to define the location of the occurrence.

A matrix object is a transient object. (These objects are in memory only). Here is a section from the Object Model pdf file. Notice there is a Matrix and a Matrix2d. A Matrix object stores 3d information that controls the location and rotation of the occurrence in the assembly space.

17

Page 18: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

(Matrices are covered in more detail in this document in a later section).

Here is an example that uses the Add method to add a ComponentOccurrence. The CreateMatrix method of the TransientGeometry is used to create a Matrix. In this example it is the identity matrix which will position this component at the origin of the assembly space.

Public Sub Demo_AddOccurrence() ' Using the ActiveDocument property. (need to have an Assembly Active) Dim oAsmDoc As AssemblyDocument Set oAsmDoc = ThisApplication.ActiveDocument ' Declare a Matrix variable get the Matrix using CreateMatrix ' of TransientGeometry Dim oMatrix As Matrix Set oMatrix = ThisApplication.TransientGeometry.CreateMatrix ' Declare a ComponentOccurrence variable. Instantiate it with ' the Add method of the Occurrences collection of the ' ComponentDefinition of the Assembly document this will add ' an occurrence from a file. Dim oOcc As ComponentOccurrence Set oOcc = oAsmDoc.ComponentDefinition.Occurrences.Add _ ("C:\Temp\Part1.ipt", oMatrix)End Sub

The picture below shows that after running the code the component has been added and the origin of the part is located at the origin of the assembly.

18

Page 19: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

The ComponentOccurrences object has other methods that allow you to add components. In this screen shot you can see the intellisense of methods for adding components.

The AddByComponentDefinition will add a component using the component of a part that is open or already exists in the assembly. The Add method used in the previous example takes a path to a file. AddWithOptions allows you to add a component using one of the representations such as a level of detail. (This method is discussed in more detail in a later section)

When you use the user interface to create an assembly you manually locate the component in the assembly space. The API will allow you to programmatically place the component at the correct location as well. To control the position of a component in the assembly you use a matrix.

In the following example the second component is placed at the same y, z location as in the previous example. However the X location for the component is two inches more in the positive

19

Page 20: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

direction on the X axis. Notice how a Vector (with 2 inches for the X value) and a Matrix are used to accomplish this. See these sections for a detailed discussion on the Vector and Matrix objects: (Vector, Matrix)

Public Sub Demo_AddOccurrence_Move_in_X() ' Using the ActiveDocument property. (need to have an Assembly Active) If ThisApplication.ActiveDocument.DocumentType <> kAssemblyDocumentObject Then Exit Sub Dim oAsmDoc As AssemblyDocument Set oAsmDoc = ThisApplication.ActiveDocument ' Get the TransientGeometry of the application Dim oTG As TransientGeometry Set oTG = ThisApplication.TransientGeometry ' Get the UnitsOfMeasure object from the active document Dim uOfM As UnitsOfMeasure Set uOfM = ThisApplication.ActiveDocument.UnitsOfMeasure ' This is a distance to move the component Dim dDistance As Double dDistance = 2 ' Convert the value into inches dDistance = uOfM.ConvertUnits(dDistance, kInchLengthUnits, kDatabaseLengthUnits) ' Create a vector to be used in the SetTranslation method Dim oVec As Vector ' Make the vector 2 inches in the X direction Set oVec = oTG.CreateVector(dDistance, 0, 0) ' Make the vector 2 inches in the Y direction, comment the line above and uncomment this ' Set oVec = oTG.CreateVector(0, dDistance, 0) ' Create a matrix Dim oMatrix As Matrix Set oMatrix = oTG.CreateMatrix ' set the translation using the vector this will position the component Call oMatrix.SetTranslation(oVec, False) ' Add the occurrence Dim oOcc As ComponentOccurrence Set oOcc = oAsmDoc.ComponentDefinition.Occurrences.Add _ ("C:\Autodesk University\AU 2009\Part1.ipt", oMatrix)

20

Page 21: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

End Sub

Here is the result after running the last two examples. Notice that the second occurrence is positioned two inches in the positive direction on the x axis.

Constraints After you have added components to the assembly you will probably want to constrain them. The AssemblyComponentDefinition has a constraints property that has methods for constraining occurrences.

Here is the object hierarchy for assembly constraints:

21

Page 22: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Here is a screenshot of intellisense showing available methods for adding constraints:

These methods to create constraints need geometry from the occurrences or work features such as a workplane. You can use the B-Rep part of the API to get the geometry to use in the constraint methods. LocateUsingPoint or FindUsingRay allow you to find geometry in the part. There is a detailed discussion later in this document on this part of the API. (B-Rep)

You can also get the selected objects from the user to use for the constraint. (such as B-Rep objects). This example applies a mate constraint between to selected faces.

22

Page 23: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Public Sub mateConstraintUsingSelection()

' Set a reference to the assembly component definintion. Dim oAsmCompDef As AssemblyComponentDefinition Set oAsmCompDef = ThisApplication.ActiveDocument.ComponentDefinition ' Set a reference to the select set. Dim oSelectSet As SelectSet Set oSelectSet = ThisApplication.ActiveDocument.SelectSet ' Validate the correct data is in the select set. If oSelectSet.Count <> 2 Then MsgBox "You must select the two entities valid for mate." Exit Sub End If

' Get the two entities from the select set. Dim oBrepEnt1 As Object Dim oBrepEnt2 As Object Set oBrepEnt1 = oSelectSet.Item(1) Set oBrepEnt2 = oSelectSet.Item(2) ' Create the insert constraint between the parts. Dim oMate As MateConstraint Set oMate = oAsmCompDef.Constraints.AddMateConstraint(oBrepEnt1, oBrepEnt2, 0)End Sub

In the previous example the SelectSet was used to get the geometry for the constraint. You can also use the B-Rep API to get the geometry. This example gets a vertex from two occurrences for the constraint.

Public Sub mateConstraintOfVertices() ' make sure ActiveDocument is an assembly If ThisApplication.ActiveDocument.DocumentType <> kAssemblyDocumentObject Then Exit Sub ' Get the component definition of the assembly. Dim oAsmDef As AssemblyComponentDefinition Set oAsmDef = ThisApplication.ActiveDocument.ComponentDefinition ' make sure there are at least 2 occurrences If oAsmDef.Occurrences.Count < 2 Then Exit Sub ' Get the first and second componentOccurrence Dim oOcc1 As ComponentOccurrence, oOcc2 As ComponentOccurrence Set oOcc1 = oAsmDef.Occurrences(1)

23

Page 24: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Set oOcc2 = oAsmDef.Occurrences(2) ' Declare a Vertex object and instatiate it using the first Vertex of ' of the first occurrence. Dim oVertex1 As Vertex Set oVertex1 = oOcc1.SurfaceBodies.Item(1).Vertices.Item(1) ' Declare a vertex object and instantiate is using the part (definition) ' of the second occurrence. Dim oVertex2 As Vertex Set oVertex2 = oOcc2.SurfaceBodies.Item(1).Vertices.Item(8) ' Declare and MateConstraint object and instantiate it using the ' AddMateConstraint of the AssemblyComponentDefinition created above (oAsmDef) ' pass in the Vertex object and the second vertex object, make the offset zero Dim oMateConstraint As MateConstraint Set oMateConstraint = oAsmDef.Constraints.AddMateConstraint( _ oVertex1, oVertex2, 0) End Sub

In some cases you may need to use a proxy object to apply constraints. A proxy object is a reference to the part as if it existed in the assembly space. (This is not obvious in the user interface).

This example creates a constraint between workplanes. Notice how the ComponentOccurrence.Definition allows you to get to the workplanes in the part. The AddMateConstraint method needs a WorkPlaneProxy object. This object is created using the CreateGeometryProxy method of the ComponentOccurrence.

Public Sub mateConstraintOfWorkPlanes_Proxy() Dim oAsmCompDef As AssemblyComponentDefinition Set oAsmCompDef = ThisApplication.ActiveDocument.ComponentDefinition ' Get references to the two occurrences to constrain. ' This arbitrarily gets the first and second occurrence. Dim oOcc1 As ComponentOccurrence Set oOcc1 = oAsmCompDef.Occurrences.Item(1) Dim oOcc2 As ComponentOccurrence Set oOcc2 = oAsmCompDef.Occurrences.Item(2) ' Get the XY plane from each occurrence. This goes to the

24

Page 25: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

' component definition of the part to get this information. ' This is the same as accessing the part document directly. ' The work plane obtained is in the context of the part, ' not the assembly. Dim oPartPlane1 As WorkPlane Set oPartPlane1 = oOcc1.Definition.WorkPlanes.Item(3) Dim oPartPlane2 As WorkPlane Set oPartPlane2 = oOcc2.Definition.WorkPlanes.Item(3) ' Because we need the work plane in the context of the assembly ' we need to create proxies for the work planes. The proxies ' represent the work planes in the context of the assembly. Dim oAsmPlane1 As WorkPlaneProxy Call oOcc1.CreateGeometryProxy(oPartPlane1, oAsmPlane1) Dim oAsmPlane2 As WorkPlaneProxy Call oOcc2.CreateGeometryProxy(oPartPlane2, oAsmPlane2) ' Create the constraint using the work plane proxies. Call oAsmCompDef.Constraints.AddMateConstraint(oAsmPlane1, oAsmPlane2, 0)End Sub

More on ProxiesYou can get to the component definition (PartComponentDefinition) using the definition property of a ComponentOccurrence. We can think of the definition of the component as the native object. Proxies allow you to get information from the native object as it exists in the assembly. This will allow you to obtain data specifically in the assembly context. Keep in mind the geometry of a component in the assembly does not exist, only a proxy that is performing the required transformations based on the position of the part within the assembly.

This example gets a vertex from a ComponentOccurrence. This vertex is actually a VertexProxy. The x,y,z values of the vertex are printed to the immediate window. This same vertex is accessed from the PartComponentDefinition and the x,y,z values are printed. These values are in the part space. This vertex is then used to create a VertexProxy using the ComponentOccurrence.CreateGeometryProxy method. What this example shows is the relationship a Proxy object has to the native object.

Public Sub proxies_Demo1() ' make sure ActiveDocument is an assembly If ThisApplication.ActiveDocument.DocumentType <> kAssemblyDocumentObject Then Exit Sub

25

Page 26: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

' Get the component definition of the assembly. Dim oAsmDef As AssemblyComponentDefinition Set oAsmDef = ThisApplication.ActiveDocument.ComponentDefinition ' make sure there are at least 2 occurrences If oAsmDef.Occurrences.Count < 2 Then Exit Sub ' Get the second occurrence Dim oOcc As ComponentOccurrence Set oOcc = oAsmDef.Occurrences(2) ' Declare an object as a Vertex and instantiate it using ' the occurrence SurfaceBodies 1, Vertices 1 Dim oVertex As Vertex Set oVertex = oOcc.SurfaceBodies.Item(1).Vertices.Item(1) ' Use Debug.print and print out the X,Y,Z values of that vertex created ' above. Notice that the coordinates are in the assembly space. Use the ' watch window and see what vertex actually is. (VertexProxy) Debug.Print "X,Y,Z of vertex in the Assembly space" Debug.Print oVertex.Point.X Debug.Print oVertex.Point.Y Debug.Print oVertex.Point.Z ' Declare a PartComponentDefinition and instantiate it using the ' Definition property of the Occurrence created above. Dim oPartCompDef As PartComponentDefinition Set oPartCompDef = oOcc.Definition ' Set the vertex variable created above to the same vertex in the ' part. SurfaceBodies 1, Vertices 1 Set oVertex = oPartCompDef.SurfaceBodies.Item(1).Vertices.Item(1) ' Use Debug.print and print out the X,Y,Z values of that vertex created ' above. Notice that the coordinates are in the part space. Use the ' watch window and see what vertex actually is. (Vertex) Debug.Print "X,Y,Z of vertex in the PartComponentDefinition" Debug.Print oVertex.Point.X Debug.Print oVertex.Point.Y Debug.Print oVertex.Point.Z ' Declare a VertexProxy variable and instantiate it using ' CreateGeometryProxy of the occurrence created above oOcc. Pass in the ' vertext from above and the VertexProxy variable. Dim oVertexProxy As VertexProxy

26

Page 27: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Call oOcc.CreateGeometryProxy(oVertex, oVertexProxy) ' Use Debug.print and print out the X,Y,Z values of that VertexProxy created ' above. Notice that the coordinates are in the Assembly space. Debug.Print "X,Y,Z of the vertex using VertexProxy - same as vertex in assembly space" Debug.Print oVertexProxy.Point.X Debug.Print oVertexProxy.Point.Y Debug.Print oVertexProxy.Point.Z

End Sub

Level of DetailThe API provides access to the different representations through the RepresentationsManager object. The AssemblyComponentDefinition has a RepresentationsManager property that will allow you to access this object. Here is the hierarchy for objects related to representations in an assembly:

The RepresentationsManager object has methods for accessing the representation objects:

27

Page 28: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

You use the LevelOfDetailRepresentations property of the RepresentationsManager object to instantiate a LevelOfDetailRepresentations object. This object will allow you to use the API to create Level of details for an assembly.

This example suppresses the second ComponentOccurrence and creates a Level of detail. If the Level of detail already exists the user can activate it.

Public Sub levelOfDetail_demo1() If ThisApplication.ActiveDocument.DocumentType <> kAssemblyDocumentObject Then Exit Sub ' Declare a AssemblyComponentDefinition variable intstantiate it with the ActiveDocument ' componentdefinition Dim oAsmDef As AssemblyComponentDefinition Set oAsmDef = ThisApplication.ActiveDocument.ComponentDefinition ' Declare a RepresentationsManger and instantiate it with the ' RepresentationsManager property of the AssemblyComponentDefinition Dim oRepManager As RepresentationsManager Set oRepManager = oAsmDef.RepresentationsManager ' Declare a LevelOfDetailRepresentations using the RepresentionsManager ' of the assembly componentdefinition created above Dim oLODReps As LevelOfDetailRepresentations Set oLODReps = oRepManager.LevelOfDetailRepresentations ' Declare a LevelOfDetailRepresentation variable Dim oLODRep As LevelOfDetailRepresentation ' See if "MY LOD1" already exists, if it does ask the user

28

Page 29: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

' if they want to activate it and then end the procedure For Each oLODRep In oRepManager.LevelOfDetailRepresentations If oLODRep.Name = "My LOD1" Then Dim intYesNo As Integer intYesNo = MsgBox("MY LOD1 already exists - Activate?", vbYesNo) If intYesNo = 6 Then oLODReps.Item("My LOD1").Activate End If End ' stop the procedure End If Next oLODRep ' Create the Level of Detail Set oLODRep = oLODReps.Add("My LOD1") ' Suppress the second occurrence in the Assembly. If oAsmDef.Occurrences.Count < 2 Then Exit Sub oAsmDef.Occurrences.Item(2).Suppress ' Save the Assembbly document, which saves the Level Of Detail ThisApplication.ActiveDocument.Save

'Activate the new Level of detail. oLODReps.Item("My LOD1").Activate 'uncomment this to make the Master Level of detail current 'oAsmDef.RepresentationsManager.LevelOfDetailRepresentations.Item("Master").Activate

End Sub

To add open an assembly using a Level of Detail use the Documents.OpenWithOptions(). To place a component using Level of detail use AssemblyComponentDefinition.Occurrences.AddWithOptions. These methods determine which Level of detail to use (or another type of representation) using a NameValueMap. A NameValueMap object is created using the CreateNameValueMap method of the TransientObjects collection of the Inventor.Application. Here is a screen shot of the intellisense for this object. We will use the Add method to set which Level of detail to use.

29

Page 30: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

This example opens an assembly using a Level of detail. Notice that the Add method of the NameValueMap takes a couple of strings. One of these is used to determine which type of representation to set and the other is the name of the Level of detail.

Public Sub AddOccurrenceWithRepresentations() ' Set a reference to the assembly component definintion. ' This assumes an assembly document is open. Dim oAsmCompDef As AssemblyComponentDefinition Set oAsmCompDef = ThisApplication.ActiveDocument.ComponentDefinition

' Set a reference to the transient geometry object. Dim oTG As TransientGeometry Set oTG = ThisApplication.TransientGeometry

' Create a matrix. A new matrix is initialized with an identity matrix. Dim oMatrix As Matrix Set oMatrix = oTG.CreateMatrix

' Create a new NameValueMap object Dim oOptions As NameValueMap Set oOptions = ThisApplication.TransientObjects.CreateNameValueMap ' Set the representations to use when creating the occurrence. Call oOptions.Add("LevelOfDetailRepresentation", "My LOD1") ' Add the occurrence. Dim oOcc As ComponentOccurrence Set oOcc = oAsmCompDef.Occurrences.AddWithOptions("C:\Autodesk University\AU 2009\Assembly2.iam", oMatrix, oOptions)End Sub

30

Page 31: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

The following sections provide a detailed discussion of Vector, Matrix and the B-Rep API.

Vector Objects

A vector is a convenient way to specify magnitude and direction. Internally a vector consists of three values; its x, y, and z components. (A 2d vector only has x and y components.) Although its data is very simple, the Vector object also supports a rich set of methods and properties that allow you to easily query, manipulate, and compare vectors. Let’s look at a couple of examples of how vectors are used.

A common use of vectors is to define the movement of an object. This is typically referred to as the translation of an object, which means it is moved in space without any rotation taking place. For example the vector (3,1,0) would define the movement of an object 3 units in the x direction, 1 unit in the y direction, and 0 units in the z direction resulting in a total move of 3.162 units, which is illustrated below.

 Another common use of vectors is to use them as a convenient way of specifying a direction. In the previous example a vector was used to define a direction and magnitude to specify the direction and distance to move a part. When a vector is only used to specify a direction then usually the UnitVector object is used since the magnitude of a UnitVector is always one. An example of when vectors are used to define direction is when you get orientation information from the geometry transient objects. For example, the Cylinder object supports the AxisVector property that returns a UnitVector object. This vector defines the direction of the axis of the cylinder.

As stated earlier, the functionality that makes the Vector object so powerful are the methods and properties it supports. Let’s look at some of the more commonly used methods and how and why they’re used.

When defining a rectangular coordinate system you typically have a point that defines the origin and three vectors that define the x, y, and z axis directions. (These can be unit vectors since the magnitude doesn’t matter.) For a valid rectangular coordinate system these vectors have to follow some rules:

31

Page 32: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

1. The y-axis vector must be perpendicular to the x-axis.2. The z-axis must be perpendicular to the x and y axes and for a right-hand coordinate

system (which Inventor uses) it must be in the direction that follows the right-hand rule.

The trick is how to easily create three vectors that follow these rules. Let’s look at a specific case and how to solve it. Let’s say we want to define a coordinate system where the x-axis points in the direction defined by the vector (3, 7, 6), and we want the y-axis to point “up”, where up is in the positive Y direction. Finally the z-axis just needs to be valid based on the y and z axes. First let’s look at a utility that makes what could be a nightmare to compute quite easy.

With vectors there’s an operation called cross product, where you input two vectors and obtain a third as the result. Any two vectors (as long as they’re not parallel) define a plane. If you take any two vectors and put their tails together, both vectors will lie in a single plane. Performing a cross product with these vectors returns another vector that is perpendicular to that plane. The picture to the right illustrates this by showing two vectors (labeled x and y) and crossing them to obtain the vector z. The vector z can be in either of two directions depending on which order you cross x and y. In the example shown, x is crossed into y which results in the z shown. This follows the right-hand rule: flatten your hand, extend your thumb, and point your fingers along the x-axis. Now, going from the x-axis towards the y-axis (in the direction that’s the shortest between them), curl your fingers so they curl towards the y-axis. You’re thumb will be pointing in the direction of the positive z-axis. If you had started with your fingers pointing in the y-axis direction and then curled them toward the x-axis your thumb would be pointing in the opposite direction.

Using this concept of crossing two vectors let’s see how we can construct the coordinate system specified earlier. Here are the steps and then we’ll look at the code to perform these steps.

1. Create a vector that defines the known x-axis, (3,7,6).2. Create a vector that defines the y-axis direction, (0,1,0). (We know at this point that this

is not the correct y-axis. This just defines the general direction we want the y-axis to go in.)

3. Cross the x-axis into the y-axis to get the z-axis. This results in the correct z-axis vector.4. Cross the z-axis into the x-axis to get the y axis. This results in the correct y-axis vector.

Public Sub CreateCoordSystem() ' Set a reference to the TransientGeometry object. Dim oTG As TransientGeometry Set oTG = ThisApplication.TransientGeometry ' Create a vector for the x-axis. Dim oXAxis As UnitVector Set oXAxis = oTG.CreateUnitVector(3, 7, 6) ' Create a vector in the general y-axis direction. Dim oYAxis As UnitVector Set oYAxis = oTG.CreateUnitVector(0, 1, 0) ' Cross the x into the y to get the z-axis. Dim oZAxis As UnitVector

32

Page 33: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Set oZAxis = oXAxis.CrossProduct(oYAxis) ' Cross the z into the x to get the correct y axis. Set oYAxis = oZAxis.CrossProduct(oXAxis) ' Display the results. Debug.Print "x-axis: " & oXAxis.X & ", " & oXAxis.Y & ", " & oXAxis.Z Debug.Print "y-axis: " & oYAxis.X & ", " & oYAxis.Y & ", " & oYAxis.Z Debug.Print "z-axis: " & oZAxis.X & ", " & oZAxis.Y & ", " & oZAxis.Z End Sub

Here are some of the other functions supported by the vector object. The following methods allow you to compare two vectors in various ways: AngleTo, IsEqualTo, IsParallelTo and IsPerpendicularTo. The following methods allow you to combine to vectors: AddVector, SubtractVector, CrossProduct, and DotProduct. The Vector object (vs. the UnitVector object) also supports some functionality that deals with the magnitude of the vector. These are Length, Normalize (which makes the length 1 unit), and ScaleBy. Finally, occasionally you may have a Vector and need a UnitVector or vice versa. The AsUnitVector method on the Vector and AsVector on the UnitVector allow you to easily obtain the opposite type.

Matrix Objects

A matrix is defined as a rectangular array of numbers. For three-dimensional space, Inventor supports the Matrix object and for two-dimensional space it supports the Matrix2d object. The Matrix object is a 4x4 rectangular array (four columns and four rows), while the Matrix2d is a 3x3 rectangular array. A typical 3d 4x4 matrix is shown below. The Matrix object encapsulates these 16 values. Considering the data, a matrix is a simple object but it quickly gets much more complex as we try to understand how to use this information. Out of all the transient geometry objects, the Matrix is the least understood and causes programmers the most problems.

33

1 0 0 0

0 1 0 0

0 0 1 0

0 0 0 1

Page 34: AU09 CP318-1 Inventor API Intro Assemblies

X-A

xis

Y-A

xis

Origin

Z-Axis

1 0 00 0 1 00 0 0 10 0 0 01

Introduction to Autodesk® Inventor® API and Assemblies

The following describes a practical approach to matrices. The Matrix is used in two ways. The first is using the matrix to define a coordinate system. The second is a matrix to define a transformation. We’ll look at both of these in detail in the discussion that follows. Inventor supports both 3d and 2d matrices, but since a 3d is the most commonly used the discussion below is limited to it, however the same concepts apply to both.

A Matrix as a Coordinate SystemFirst, let’s look at what a coordinate system consists of and then we’ll see how a matrix provides this information. A coordinate system defines a position in space and an orientation. For three-dimensional space the origin is a 3d coordinate point (x.y.z) defined relative to model space. This defines the position of the coordinate system. The orientation is defined by specifying the direction of the x, y, and z axes.

For a rectangular coordinate system, which is what Inventor always uses, there are certain rules that are enforced as was discussed earlier. These are that the x-axis and y-axis are perpendicular to each other and the z-axis is perpendicular to both the x-axis and y-axis and follows the right-hand rule. (Another way to determine the direction of the z-axis is that if the x-axis points to the right and the y-axis points up, then the z-axis will point toward you. Also, all three axis vectors must be normalized, which means the magnitude of each vector must be 1.

The figure above illustrates how a matrix encapsulates this information. First, when looking at or manipulating a matrix you can always ignore the bottom row. The bottom row will always have the values 0, 0, 0, 1. The other twelve values define the coordinate system. The first column defines the x-axis direction (1,0,0). The second column defines the y-axis direction (0,1,0), and the third column defines the z-axis direction (0,0,1). The last column defines the position of the coordinate system’s origin (0,0,0). This default matrix is a special matrix known as an identity matrix. It’s special because it defines a coordinate system that is identical to the

34

Page 35: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

base coordinate system. The origin is at (0,0,0) and the x, y, and z axes are in the same direction as the base coordinate system axes.

Let’s look at how to apply this information to define a specific coordinate system. For this example we want to define a coordinate system whose position is at (10,5,0) and is rotated 45° around the z-axis. The result will be a coordinate system as shown in the figure below.

Let’s look first at the x-axis. If we rotate the coordinate system 45° around the z-axis then the x-axis is pointing 45° in the positive x and y directions. A simple vector that pointed in this direction could be defined as (1, 1, 0), but since these vectors need to be normalized it results in (0.707, 0.707, 0). The y-axis points in the negative x and positive y direction which results in the vector (-0.707, 0.707, 0). The z-axis remains unchanged (0, 0, 1). Finally, the position of the matrix is defined at (10, 5, 0). The resulting matrix is shown below.

The code below demonstrates one approach to constructing the matrix above. It takes advantage of some features in the API. First, when defining the axis vectors it uses the UnitVector type of vector. This guarantees that the axis vectors will be normalized since unit vectors always have a magnitude of 1. Second, it uses the SetCoordinateSystem method of the Matrix object to define the matrix, which simplifies setting the correct values for the matrix. When defining the coordinate system, remember that all units will be internal units which means distances are defined in centimeters.

Public Sub MatrixDefineSample()

35

0.707 -0.707 0 10

0.707 0.707 0 5

0 0 1 0

0 0 0 1

Page 36: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

' Set a reference to the TransientGeometry object and create a variable for Pi. Dim oTG As TransientGeometry Set oTG = ThisApplication.TransientGeometry Dim dPi As Double dPi = Atn(1) * 4 ' Define the origin point. Dim oOrigin As Point Set oOrigin = oTG.CreatePoint(10, 5, 0) ' Define the axis vectors. Pi/4 is 45 degrees in radians. Dim oXAxis As UnitVector Dim oYAxis As UnitVector Dim oZAxis As UnitVector Set oXAxis = oTG.CreateUnitVector(Cos(dPi / 4), Sin(dPi / 4), 0) Set oYAxis = oTG.CreateUnitVector(-Cos(dPi / 4), Sin(dPi / 4), 0) Set oZAxis = oTG.CreateUnitVector(0, 0, 1) ' Create the matrix and define the desired coordinate system. Dim oMatrix As Matrix Set oMatrix = oTG.CreateMatrix Call oMatrix.SetCoordinateSystem(oOrigin, oXAxis.AsVector, _ oYAxis.AsVector, oZAxis.AsVector)End Sub

Instead of using the SetCoordinateSystem method you can set the matrix one cell at a time. Using the Cell property of the matrix you can read and write an individual cell. The code below results in the same matrix as the SetCoordinateSystem method defines in the sample above. As you can see, using the SetCoordinateSystem is easier and makes the program more readable. However, sometimes setting individual cells is convenient when make small changes to a matrix.

' Create the matrix and define the desired coordinate system. Dim oMatrix As Matrix Set oMatrix = oTG.CreateMatrix oMatrix.Cell(1, 1) = oXAxis.X oMatrix.Cell(2, 1) = oXAxis.Y oMatrix.Cell(3, 1) = oXAxis.Z oMatrix.Cell(1, 2) = oYAxis.X oMatrix.Cell(2, 2) = oYAxis.Y oMatrix.Cell(3, 2) = oYAxis.Z

36

Page 37: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

oMatrix.Cell(1, 3) = oZAxis.X oMatrix.Cell(2, 3) = oZAxis.Y oMatrix.Cell(3, 3) = oZAxis.Z oMatrix.Cell(1, 4) = oOrigin.X oMatrix.Cell(2, 4) = oOrigin.Y oMatrix.Cell(3, 4) = oOrigin.Z

The code below is also useful when working with matrices. It dumps out the contents of a matrix to allow you to better visualize it.

Public Sub DumpMatrix(oMatrix As Matrix) Dim i As Integer For i = 1 To 4 Debug.Print Format(oMatrix.Cell(i, 1), "0.000000") & ", " & _ Format(oMatrix.Cell(i, 2), "0.000000") & ", " & _ Format(oMatrix.Cell(i, 3), "0.000000") & ", " & _ Format(oMatrix.Cell(i, 4), "0.000000") NextEnd Sub

Running this program results in the output shown below when the matrix created previously is provided as input.

0.707107, -0.707107, 0.000000, 10.0000000.707107, 0.707107, 0.000000, 5.0000000.000000, 0.000000, 1.000000, 0.0000000.000000, 0.000000, 0.000000, 1.000000

Placing Assembly Occurrences

The most common use of matrices is when working with assembly occurrences. When placing an occurrence into an assembly with the API you use a matrix to specify the position and orientation of the occurrence. The matrix specifies the position of the parts or subassembly’s coordinate system within the assembly. Let’s look at a specific example using the part to the right. Creating a part similar to the one to the right can be useful while debugging your programs that use matrices because since it looks like a coordinate system it allows you to better visualize the result of the matrix. The part is constructed so the corner connecting the two arrows is at the origin of the part coordinate system and the arrow along the X axis is longer to make it easy to identify.

37

Page 38: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

If you open a new assembly and manually place an instance of this part into the assembly you’ll see that the part is positioned as the origin of the assembly and the axes are the same as the assembly axes. When the first part is placed manually into an assembly, internally Inventor positions it using an identity matrix. If we add the following code to the previous program it will place a part at (10,5,0) and rotated 45° around the z-axis.

' Place a part into the active assembly using the defined matrix. Dim oOcc As ComponentOccurrence Set oOcc = ThisApplication.ActiveDocument.ComponentDefinition.Occurrences.Add( _ "C:\Temp\Part.ipt", oMatrix)

This creates the resulting assembly shown below where the occurrence at the upper-right is the one placed using the API.

You can reposition an occurrence by editing its matrix which can be retrieved or set using the Transformation property of the ComponentOccurrence object. Below are some examples of edits to the position of an occurrence. Properties and methods on the Matrix object simplify setting the matrix values for common operations.

Public Sub ModifyOccurrence() ' Get a reference to an existing occurrence. Dim oDoc As AssemblyDocument Set oDoc = ThisApplication.ActiveDocument Dim oOcc As ComponentOccurrence Set oOcc = oDoc.ComponentDefinition.Occurrences.ItemByName("Part:1") Dim oTG As TransientGeometry Set oTG = ThisApplication.TransientGeometry ' Move the occurrence to (3,2,1).

38

Page 39: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Dim oMatrix As Matrix Set oMatrix = oOcc.Transformation Call oMatrix.SetTranslation(oTG.CreateVector(3, 2, 1)) oOcc.Transformation = oMatrix ' Move the occurrence 5 cm in the X direction by changing the matrix directly. Set oMatrix = oOcc.Transformation oMatrix.Cell(1, 4) = oMatrix.Cell(1, 4) + 5 oOcc.Transformation = oMatrixEnd Sub

As shown in the previous samples, the placement or repositioning of an occurrence is completely dependent on a matrix. By understanding how to construct the desired matrix you can position an occurrence at any desired position and orientation.

A Matrix Defines a Transformation

Another way to think of a matrix is that it defines a change in position and orientation. This is conceptually different than using a matrix to define a coordinate system because in this case you’re not defining an absolute position but instead are defining a delta change in position. Let’s look at how this works with an assembly occurrence. For this example let’s say that we want to rotate several occurrences 45° about the assembly’s z-axis. Using what we know so far it would be a bit of work to take the existing matrix from an occurrence and create a coordinate system that defines the new desired position. However, using the ability of a matrix to define a transformation this is quite easy because you just apply the same change (45° rotation about the z-axis) to each occurrence and the desired coordinate system comes out as the result. You do this using the TransformBy method of the Matrix object. This method applies the transform defined by one matrix to an existing matrix. The sample below illustrates this. The majority of the sample is just setting up the matrix that defines the change to apply. The rest of it is iterating through all of the occurrences and applying these changes to each one.

Public Sub RotateOccurrences() Dim oTG As TransientGeometry Set oTG = ThisApplication.TransientGeometry Dim dPi As Double dPi = Atn(1) * 4 ' Define the axis vectors. Dim oXAxis As UnitVector Dim oYAxis As UnitVector Dim oZAxis As UnitVector

39

Page 40: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Set oXAxis = oTG.CreateUnitVector(Cos(dPi / 4), Sin(dPi / 4), 0) Set oYAxis = oTG.CreateUnitVector(-Cos(dPi / 4), Sin(dPi / 4), 0) Set oZAxis = oTG.CreateUnitVector(0, 0, 1) ' Create the matrix that defines the desired transformation, ' (rotate 45 degrees around the assembly’s z-axis). Dim oTransMatrix As Matrix Set oTransMatrix = oTG.CreateMatrix Call oTransMatrix.SetCoordinateSystem(oTG.CreatePoint, _ oXAxis.AsVector, oYAxis.AsVector, oZAxis.AsVector)

' Iterate through the occurrences. Dim oDoc As AssemblyDocument Set oDoc = ThisApplication.ActiveDocument Dim oOcc As ComponentOccurrence For Each oOcc In oDoc.ComponentDefinition.Occurrences Dim oMatrix As Matrix ' Get the current matrix from the occurence. Set oMatrix = oOcc.Transformation ' Apply the transformation. Call oMatrix.TransformBy(oTransMatrix) ' Update the occurrence with the new matrix. oOcc.Transformation = oMatrix NextEnd Sub

It’s also possible to combine multiple changes within a single matrix. This capability is useful to help break up a complex transformation into smaller components (which we’ll discuss now) and when going from one base coordinate system to another (which we’ll discuss later).

To look at combining multiple changes within a single matrix, let’s say we want to rotate an occurrence 45° around the x-axis, and then 30° around the y-axis, and finally move it 5 cm in the x direction and 3 cm in the z direction. How would you define a matrix that defines the result of these changes? It’s much easier to do them one at a time and then use the matrix functionality to combine them. Multiplying two matrices together creates a new matrix that contains the transforms of both of them combined. The order that you multiply them makes a difference because the changes are applied in order. The method I typically use to do this is the TransformBy method. This takes the current matrix and multiplies another matrix with it.

40

Page 41: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Conceptually, you have a matrix and transform it by the change defined by another matrix. Let’s look at it in practice to solve the problem presented above.

Public Sub MultipleTransforms(oOcc As ComponentOccurrence) Dim oTG As TransientGeometry Set oTG = ThisApplication.TransientGeometry Dim dPi As Double dPi = Atn(1) * 4 ' Create a matrix that defines a 45° rotation around the x-axis. Dim oTransMatrix As Matrix Set oTransMatrix = oTG.CreateMatrix Call oTransMatrix.SetToRotation(dPi / 4, oTG.CreateVector(1, 0, 0), _ oTG.CreatePoint(0, 0, 0)) ' Create a matrix that defines a 30° rotation around the y-axis and apply it. Dim oTempMatrix As Matrix Set oTempMatrix = oTG.CreateMatrix Call oTempMatrix.SetToRotation(dPi / 6, oTG.CreateVector(0, 1, 0), _ oTG.CreatePoint(0, 0, 0)) Call oTransMatrix.TransformBy(oTempMatrix)

' Create a matrix that defines a 3 cm move in the z direction and apply it. oTempMatrix.SetToIdentity Call oTempMatrix.SetTranslation(oTG.CreateVector(0, 0, 3)) Call oTransMatrix.TransformBy(oTempMatrix) ' Now apply the built up transformation to the occurrence. Dim oMatrix As Matrix Set oMatrix = oOcc.Transformation Call oMatrix.TransformBy(oTransMatrix) oOcc.Transformation = oMatrixEnd Sub

This example is not that much different from what we’ve already looked at except it is applying each matrix to another matrix to build up a series of transforms. This also takes advantage of some other functions supported by the Matrix object to make manipulating it easier. For

41

Page 42: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

example the rotations are defined using the SetToRotation method. The SetToIdentity method is also used to reinitialize the matrix to an identity matrix.

The other area where a matrix is very useful is in transforming coordinates from one modeling coordinate system to another. For example, let’s say you have a work point in a part and that part has been placed into an assembly. Now you want to find the position of that work point with respect to the coordinate system of another part that’s in the assembly. For this specific example, let’s say we have a part that contains several work points. We want to write a program that will create copies of the work points within the other part. The relationship between the two parts is defined by their current relative positions within the assembly.

The picture below illustrates the problem. The picture to the left shows the part that contains the work points. The center picture shows the part that we want to copy the work points into, and the picture on the right shows both of the parts within an assembly. Now we want to create a new set of work points in the circular part that will be in the same relative location as the work points are in the rectangular part.

To access the existing work points through the API we need to go to the part that contains the work points, which in this case is the rectangular part. When we query for the location of the points their position is returned with respect to that part’s base coordinate system. The trick is to construct a matrix that will take that coordinate and transform it into assembly space and then back down into the base coordinate system of the circular part. This new coordinate can be used to create the new work point. The program below accomplishes this.

Public Sub CopyWorkPoints(RectOcc As ComponentOccurrence, RoundOcc As ComponentOccurrence) ' Get the matrix that defines the transformation from the rectangular ' occurrence into assembly space. This is just the transformation of the occurrence. Dim oRectToRoundMatrix As Matrix Set oRectToRoundMatrix = RectOcc.Transformation ' Get the matrix that defines the transformation from the round occurrence into ' assembly space and invert it so it defines assembly space to part space.

42

Page 43: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Dim oAsmToRoundPartMatrix As Matrix Set oAsmToRoundPartMatrix = RoundOcc.Transformation oAsmToRoundPartMatrix.Invert ' Combine the two matrices to create a matrix that defines the transformation ' from the part space of the rectangular part to the part space of the round part. Call oRectToRoundMatrix.TransformBy(oAsmToRoundPartMatrix) ' Iterate through the work points in the rectangular part. Dim oWorkPoint As WorkPoint For Each oWorkPoint In RectOcc.Definition.WorkPoints ' Get the position of the work point. (This is in the part coordinate system.) Dim oPosition As Point Set oPosition = oWorkPoint.Point ' Transform this point into the other parts coordinate system. Call oPosition.TransformBy(oRectToRoundMatrix) ' Use the transformed point to create a work point in the round part. Call RoundOcc.Definition.WorkPoints.AddFixed(oPosition) NextEnd Sub

There are a couple of new principles in this program that we’ve not discussed yet. The first is that the matrix returned by the Transformation property of the ComponentOccurrence object defines the transform from the part or subassembly space represented by the occurrence into assembly space. The second is the use of the Invert method. Calling the Invert method on a matrix results in a matrix that defines the opposite transform. In this case the transform from part to model space is obtained by using the Transformation property of the round occurrence. Calling the Invert method on this matrix then creates a matrix that defines the transform from assembly space to part space.

Immediately after running the program you won’t see any difference graphically because the new points are on top of the existing points. If you look at the browser of the circular part you’ll see that it contains several new work points, and slightly moving the rectangular part allows you to see that the work points were created correctly, which is what’s shown below.

43

Page 44: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

B-Rep (Boundary Representation)

B-Rep objects will allow you to analyze an Inventor part by getting the geometry and evaluators that provide information about the faces and edges of the part (the Edge object selected by the user in the fillet feature example is an object found in the B-Rep section of the API).

The top level object in this section of the API is the SurfaceBodies collection. You can instantiate this object using the ComponentOccurrence .SurfaceBodies property. (or PartComponentDefinition.SurfaceBodies). One thing to keep in mind is that B-Rep objects only have information about the current state of the part (These objects do not have a connection to the PartFeatures collection).

Under the SurfaceBody is the FaceShell object. Many PartDocuments only have one FaceShell object. If the part is made up of two or more separate sections (unconnected volumes) then it will have multiple FaceShells. The Faces collection is Under the FaceShell object. Here is a section of the Inventor API object model to help show the hierarchy of these objects.

44

Page 45: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

The example below uses B-Rep objects to print out information about the boundary representation to the immediate window. The SurfaceBody is instantiated with a call to the PartComponentDefinition SurfaceBodies collection Item property. (The ComponentOccurrenceProxy object also has a SurfaceBodies property). Next the number of FaceShells and Faces are found. A Face object is returned by the Faces collection of the FaceShell. An Edge object is instantiated from the Edges collection of the FaceShell. From the Edge object you can get the information about the vertexes of the Edge. In this case we print the StartVertext.Point.X.

Public Sub BrepTraversal() Dim oPartCompDef As PartComponentDefinition Set oPartCompDef = ThisApplication.ActiveDocument.ComponentDefinition Debug.Print "Number of SurfaceBodies = " & oPartCompDef.SurfaceBodies.count Dim oSurfBody As SurfaceBody Set oSurfBody = oPartCompDef.SurfaceBodies(1) Debug.Print "Number of FaceShells in Surface Body 1 = " & oSurfBody.FaceShells.count Dim oFaceShell As FaceShell Set oFaceShell = oSurfBody.FaceShells(1) Debug.Print "Number of Faces in FaceShell 1 = " & oFaceShell.Faces.count

45

Page 46: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Dim oFace As Face Set oFace = oFaceShell.Faces(2) Debug.Print "Number of Edges on Face 2 = " & oFace.Edges.count Dim oEdge As Edge Set oEdge = oFace.Edges(1) Debug.Print "StartVertext X of Edge = " & oEdge.StartVertex.Point.X End Sub

This screen shot is the result of running the code above. This surface body is cube and is a very simple example. There are 6 faces in the FaceShell and 4 edges for each face.

The evaluator objects will allow you to get the details of the edges or faces in the model. The Evaluator property of a face returns a SurfaceEvaluator.

46

Page 47: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

The evaluator property of an edge will return a CurveEvaluator. In the following code snippet you can see how to pass in a two double arrays to the GetEndPoints method of the CurveEvaluator. The x value of the edge (dStartPoint(0)) is printed in the immediate window.

Dim oEval As CurveEvaluator Set oEval = oEdge.Evaluator Dim dEndPoint(0 To 2) As Double Dim dStartPoint(0 To 2) As Double Call oEval.GetEndPoints(dStartPoint, dEndPoint) Debug.Print dStartPoint(0)

Locating Objects using B-RepThe LocateUsingPoint method of the SurfaceBody allows you to find a face or other object. The LocateUsingPoint method takes the type of object to find and a 3d point. In this procedure this method is used to get a face. If a face is found at this point, (0,0,0) then the Evaluator of the face is used and the area of the face is displayed in a MsgBox.

Public Sub Demo_GetFaceAtPoint() Dim oPartDoc As PartDocument Set oPartDoc = ThisApplication.ActiveDocument Dim oBody As SurfaceBody Set oBody = oPartDoc.ComponentDefinition.SurfaceBodies.Item(1)

Dim oPoint As Point Set oPoint = ThisApplication.TransientGeometry.CreatePoint(0, 0, 0) Dim oFace As Face On Error Resume Next Set oFace = oBody.LocateUsingPoint(kFaceObject, oPoint) If Err Then

47

Page 48: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

Debug.Print Err.Description MsgBox "A face is not at the specified point." Else MsgBox "Found face with area " & oFace.Evaluator.Area & " cm^2" End IfEnd Sub

Another method of the SurfaceBody for finding objects is FindUsingRay. This method takes a starting point and a vector. It allows you to get an ObjectsEnumerator with all of the entities found along this vector. In this code snippet oFoundEnts will contain the objects found along the negative z axis. (0,0,-1). The last parameter instructs the method to only return the first object found.

Dim oTG As TransientGeometry Set oTG = ThisApplication.TransientGeometry Dim oFoundEnts As ObjectsEnumerator Dim oLocPoints As ObjectsEnumerator Call oBody.FindUsingRay(oTG.CreatePoint(0, 0, 0), _ oTG.CreateUnitVector(0, 0, -1), 0.00001, _ oFoundEnts, oLocPoints, True)

Here is an excerpt from the Inventor API help file on the FindUsingRay method:

Note:There is a precedence in the type of entities returned. The entities returned can be Vertex, Edge, or Face objects. The precedence is in that order. If the ray intersects a vertex, then that vertex is returned and none of the edges or faces that connect to that vertex are returned. If the ray intersects an edge, then that edge is returned and none of the faces that connect to the edge are returned. If the ray intersects a face, then that face is returned. If desired, you can use the functionality provided by the B-Rep portion of the API to obtain the various associated objects from the entity returned. For example if you need a face but an edge is returned, you can use the Faces property of the Edge object to get the associated faces. The start point defines the physical starting point from which to determine intersections. Any intersections behind the start point are ignored. However, the ray is infinite from the start point, so all intersections in the direction of the ray will be returned.

SummaryThank you for attending this session on the Inventor API. I hope you found the class enjoyable and valuable. In this handout I have introduced the Inventor API and covered some of the key objects used for automating assemblies. These are the AssemblyDocument, AssemblyComponentDefinition, ComponentOccurrence, Constraints, Proxy objects and Level of detail. You have also seen examples of using supporting objects such as the UnitsOfMeasure,

48

Page 49: AU09 CP318-1 Inventor API Intro Assemblies

Introduction to Autodesk® Inventor® API and Assemblies

TransientGeometry, Vectors and Matrices. Also remember that the objects in B-Rep section of the API can be used to analyze the faces and edges in a model. The Inventor API has hundreds of objects. Fortunately once you learn the core of the API you can become very productive.

I wish you every success in your efforts at mastering the Inventor API. [email protected]

Further Readingmodthemachine blog - monitored by Brian Ekins. - http://modthemachine.typepad.com/

API help file – search & overviews are very helpful getting up to speed on a topic.

This location has information and a couple of downloads. Autodesk Developer Center (There is a DevTV presentation “Introduction to Inventor programming” available for viewing).

Information about the Autodesk Developer Network - www.autodesk.com/joinadn

49