Quantcast
Channel: Manufacturing DevBlog
Viewing all 519 articles
Browse latest View live

Icon of newly created Sketch constraint stays visible

$
0
0

By Adam Nagy

When you create new constraints in a Sketch then the constraints' symbol will show in the UI. In previous releases it did not do that.

Also, it only seems to happen if nothing depends on the Sketch geometry (e.g. no Extrude) so that the document does not get updated automatically.

Constraint

In Inventor 2015 a new application setting was introduced that could be responsible for this:

Application Options >> Sketch >> 2D Sketch >> Constraint Settings >> 
Settings... >> General >> Display constraints on creation 

The constraint icons only show until you update the document. So once you call Document.Update they will disappear.

Sub AddConstraint()
  Dim doc As PartDocument
  Set doc = ThisApplication.ActiveDocument' The Skecth needs to be selected in the UI
  Dim sk As PlanarSketch
  Set sk = doc.SelectSet(1)
  sk.Edit
  Dim pc As ParallelConstraint
  Set pc = sk.GeometricConstraints.AddParallel( _
    sk.SketchLines(1), _
    sk.SketchLines(3))
  sk.ExitEdit' This makes the constraint icons disappear
  doc.Update
End Sub

HighlightSet does not work

$
0
0

By Adam Nagy

If you create a HighlightSet and add objects to it, but do not see the result, one possible explanation could be that the HighlightSet got released before you could see the result: maybe you declared the HighlightSet inside the function and so it ran out of scope and got released.

Make sure you declare the variable outside the function so that it can live on:

' Needs to be declared globally
Private hs As HighlightSet
Sub HighlightSample()
    Dim doc As AssemblyDocument
    Set doc = ThisApplication.ActiveDocument' If the HighlightSet was declared' inside the function, then when the function' ends and 'hs' goes out of scope it would get' released which would delete the' HighlightSet and would clear the' highlighting in the UI'Dim hs As HighlightSet
    Set hs = doc.CreateHighlightSet
    Dim tr As TransientObjects
    Set tr = ThisApplication.TransientObjects
    Dim c As Color
    Set c = tr.CreateColor(255, 0, 0, 0.8)
    hs.Color = c
    Dim occ As ComponentOccurrence
    Set occ = doc.ComponentDefinition.Occurrences(1)
    Dim f As Face
    Set f = occ.SurfaceBodies(1).Faces(1)
    hs.AddItem f
End Sub

Sub ClearHighlight()
    Set hs = Nothing
End Sub

Highlightset

 

Component occurrence cannot be renamed

$
0
0

By Adam Nagy

In case of some assemblies, e.g. the ones created by Design Accelerator, the name of the document or the occurrances in it cannot be changed: you get message "Request Rename Component cannot be run on document Synchronous Belts"

Changename

Design Accelerator does set the Document.DisabledCommandTypes to kNonShapeEditCmdType + kShapeEditCmdType, which is 32 + 1 = 33, and that seems to be the thing that disables those types of changes.

If you test the effect of the various CommandTypesEnum values concerning the above changes then this is what you get:

Public Sub SetDisabledCommandTypes()' Type / Can you rename occurrences? / Can you rename document?' kEditMaskCmdType = 57 (&H39) / No / No' - kNonShapeEditCmdType (32)' - kUpdateWithReferencesCmdType (16)' - kFilePropertyEditCmdType (8)' - kShapeEditCmdType (1)' kFileOperationsCmdType = 4 / Yes / Yes' kFilePropertyEditCmdType = 8 / Yes / Yes' kNonShapeEditCmdType = 32 (&H20) / No / No' kQueryOnlyCmdType = 2 / Yes / Yes' kReferencesChangeCmdType = 64 (&H40) / Yes / Yes' kSchemaChangeCmdType = 128 (&H80) / Yes / Yes' kShapeEditCmdType = 1 / Yes / Yes' kUpdateWithReferencesCmdType = 16 (&H10) / Yes / Yes' You can test the effect of the various enum values here
  ThisApplication.ActiveDocument.DisabledCommandTypes = _
    kNonShapeEditCmdType
End Sub

If you remove the kNonShapeEditCmdType flag from the DisabledCommandTypes property of an assembly document (e.g. by setting it to 0) then you could rename the document and its occurrences. I do not suggest that you do that though; it's just to test that that is the only setting that prevents you from doing those changes in a Design Accelerator assembly.

Add external iLogic Rule to Event Trigger

$
0
0

By Adam Nagy

Let's say we have a drawing (e.g. MyDrawing.idw) that has the following iLogicRules Event Triggers setup:

Rules1

We would like to remove the MyDocumentRule document/internal Rule from the Before Save Document event and add MyExternalRule external Rule instead. For testing purposes the external rule ony does this:

MsgBox("MyExternalRule got executed!")

... and MyDocumentRule does this:

MsgBox("MyDocumentRule got executed!")

There is no API to change the Event Triggers settings, however you can do it by modifying property sets used by iLogic for storing the relevant information. My colleague, Mike Deck, looked into this and came up with the following solution.

You can create a template/seed document by hand that has the Event Triggers setup you need and then copy those settings into other documents programmatically. The attached EventDrivenRulesCopy.iLogicVb external Rule can do the copying for you - Download EventDrivenRulesCopy

It only works on external rules. In fact, if the document has event-driven internal rules, this program will delete the Event Triggers for them. It does this for the sake of simplicity: it is copying the exact set of triggers from the source to the destination, without trying to merge them.

Please make a backup of your destination documents before running this, or run it in a temporary project.

This rule will copy the settings for event driven rules from a seed document to all the documents you select. The seed document must have been saved previously. The rule will copy only from part to part, from assembly to assembly, or from drawing to drawing.

To run it:
- Open the seed document. Ensure that this document has all the event-driven external rule links that you want.
- Run the rule. It brings up a file selection dialog.
- Multi-select the destination documents. Make sure you don’t select the seed document in this group.

Note that if the seed document has any event-driven rules that run internal rules, the rule will show an error message and not continue. This is because it is not set up to copy internal rules. It just copies the links to external rules.

Also note that if the destination documents already have some event-driven rules settings (with or without internal rules), this rule will overwrite them. It will replace them with the rule settings from the seed part. It is not smart enough to merge the two sets of rules. (It doesn’t delete the rules themselves: it only deletes the event trigger information.)

The rule can also be used to delete the event-driven rules in the destination documents. It copies the settings from the seed document. So if the seed document has no event-driven rules, it will make sure that the destination documents also have none.

Based on the above info I created a new drawing document called EventSettingsTemplate.idw, added EventDrivenRulesCopy.iLogicVb, and set up the Event Triggers like so:

Rules2

Once this document was saved and still active, I ran EventDrivenRulesCopy external Rule and selected the drawing file I wanted to modify in the first place, MyDrawing.idw. After that I checked if the settings were copied OK:

Rules3

I also modied the document and saved it to see if all is working fine and I got the expected message box:

Rules4

 

OnCloseDocument not called for referenced part document

$
0
0

By Adam Nagy

If you have a part document open on it's own and a currently open assembly references it too, then if you close the part document in the UI then OnCoseDocument is not called.

This is pointed out in the API help file as well under the Remarks section of ApplicationEvents.OnCloseDocument Event:

This means if the file is referenced from an assembly, OnOpenDocument will not fire if a loaded file referenced in an openassembly is opened again, as internally this file is already open. Conversely, if a document is closed, the document is not really closed unless that was the final view and the document is not referenced by any other open documents.

If you want to investigate when various events get fired, you can use "C:\Users\Public\Documents\Autodesk\Inventor 2015\SDK\DeveloperTools\Tools\EventWatcher" sample project.

UserForm function not listed in Macros dialog

$
0
0

By Adam Nagy

Let's say we have a VBA project with a Class, a UserForm and a Module, each with a single function in it:

VBA1
When checking in the Macros dialog only the Module's function (MyModuleFunction) will be shown:

VBA2

This is as designed. Both the Class and the UserForm hide their properties and functions from outside because those are instance specific. In other words, if you want to call a function of a UserForm you have to create a function in a Module which will create an instance of the UserForm and through that then you can access the form's properties and call its functions, including the one to show the form:

Public myUserForm As UserForm1

Sub MyModuleFunction()
  ' We create an instance of the form
  Set myUserForm = New UserForm1' Now we can access the form's functions' and properties through the variable ' named "myUserForm" ' If you want to show it as modal,' i.e. all the other UI is disabled' until the dialog is dismissed, then' just delete the word "vbModeless"' from the below code
  Call myUserForm.Show(vbModeless)
End Sub

Now if you call MyModuleFunction, it will show our form:

VBA3

  

Create transient 3D arrow with ClientGraphics

$
0
0

By Adam Nagy

As mentioned here, you can create TransientBRep objects and then use them for ClientGraphics. This makes it easy to create 3D shapes, e.g. cylinders and cones, that we could use to create a 3D arrow.

The Inventor API Help already contains a VBA sample that does just that :)

Public Sub ClientGraphics3DPrimitives()
  Dim oDoc As Document
  Set oDoc = ThisApplication.ActiveDocument' Set a reference to component definition of the active document.' This assumes that a part or assembly document is active
  Dim oCompDef As ComponentDefinition
  Set oCompDef = ThisApplication.ActiveDocument.ComponentDefinition' Check to see if the test graphics data object already exists.' If it does clean up by removing all associated of the client ' graphics from the document. If it doesn't create it
  On Error Resume Next
  Dim oClientGraphics As ClientGraphics
  Set oClientGraphics = _
    oCompDef.ClientGraphicsCollection.Item("Sample3DGraphicsID")
  If Err.Number = 0 Then
    On Error GoTo 0' An existing client graphics object was successfully ' obtained so clean up
    oClientGraphics.Delete' Update the display to see the results
    ThisApplication.ActiveView.Update
  Else
    Err.Clear
    On Error GoTo 0' Set a reference to the transient geometry object ' for user later
    Dim oTransGeom As transientGeometry
    Set oTransGeom = ThisApplication.transientGeometry' Create the ClientGraphics object.
    Set oClientGraphics = _
      oCompDef.ClientGraphicsCollection.Add("Sample3DGraphicsID")' Create a new graphics node within the client graphics objects
    Dim oSurfacesNode As GraphicsNode
    Set oSurfacesNode = oClientGraphics.AddNode(1)

    Dim oTransientBRep As TransientBRep
    Set oTransientBRep = ThisApplication.TransientBRep

    ' Create a point representing the center of the bottom of ' the cone
    Dim oBottom As Point
    Set oBottom = _
      ThisApplication.transientGeometry.CreatePoint(0, 0, 0)' Create a point representing the tip of the cone
    Dim oTop As Point
    Set oTop = _
      ThisApplication.transientGeometry.CreatePoint(0, 10, 0)' Create a transient cone body
    Dim oBody As SurfaceBody
    Set oBody = oTransientBRep.CreateSolidCylinderCone( _
      oBottom, oTop, 5, 5, 0)' Reset the top point indicating the center of the top of ' the cylinder
    Set oTop = ThisApplication.transientGeometry.CreatePoint( _
      0, -40, 0)' Create a transient cylinder body
    Dim oCylBody As SurfaceBody
    Set oCylBody = oTransientBRep.CreateSolidCylinderCone( _
      oBottom, oTop, 2.5, 2.5, 2.5)' Union the cone and cylinder bodies
    Call oTransientBRep.DoBoolean( _
      oBody, oCylBody, kBooleanTypeUnion)' Create client graphics based on the transient body
    Dim oSurfaceGraphics As SurfaceGraphics
    Set oSurfaceGraphics = oSurfacesNode.AddSurfaceGraphics(oBody)' Update the view to see the resulting curves
    ThisApplication.ActiveView.Update
  End If
End Sub

The result:

Arrow
 

 

Suppress constraints with similar name

$
0
0

By Adam Nagy

If components (e.g. constraints) with names that are the same until the last number part are logically connected, and so you want to find them, then the easiest might be to use Regular Expressions.

In this VBA sample we check the pattern or main part of the constraint's name so that we can match it against other constraints. If we find such constraints we suppress those too:

Sub SuppressConstraintsWithNamePattern()
  Dim doc As AssemblyDocument
  Set doc = ThisApplication.ActiveDocument' Get the currently selected constraint
  Dim c As AssemblyConstraint
  Set c = doc.SelectSet(1)' Easiest is to use Regular Expressions' to get the ending number.' E.g. if we have "Con1_23_12" it' will return "Con1_23_" and "12",' for "Con:12:32" it returns' "Con:12:" and "32"' Useful web pages:' https://www.udemy.com/blog/vba-regex/' http://www.rubular.com/r/qMjioXRiOG
  Set re = CreateObject("vbscript.regexp")
  re.pattern = "^(.*?)([0-9]*)$"' If we run into an error we just continue
  On Error Resume Next
  Dim matches As Object
  Set matches = re.Execute(c.Name)
  Dim pattern As String
  pattern = matches(0).SubMatches(0)' Nothing to do if no pattern found' in name of constraint
  If pattern = "" Then Exit Sub' Now iterate through the other' constraints to see if any exists' with a similar name
  For Each c In doc.ComponentDefinition.Constraints
    Set matches = re.Execute(c.Name)
    Dim s As String
    s = matches(0).SubMatches(0)' If its name has the same pattern then' suppress it
    If s = pattern Then c.Suppressed = True
  Next
End Sub

When running the code we get this:

Regex

 


Get outer profile loop in sketch

$
0
0

By Adam Nagy

If you want to find the outermost profile loop in a sketch then you can just create a temporary Profile from all the sketch entities and then check the first ProfilePath in it. That should be the outer loop. If there are multiple outer loops then you would need to check the other ProfilePath's too with AddsMaterial = True. Also if two paths are intersecting then you cannot be sure which one of those you'll get back - see below pics.

Here is a VBA code that shows how to do it:

Sub HighlightOuterSketchLoop()' You need to be inside the sketch
  Dim sk As PlanarSketch
  Set sk = ThisApplication.ActiveEditObject
  Dim doc As Document
  Set doc = ThisApplication.ActiveDocument
  Dim tm As TransactionManager
  Set tm = ThisApplication.TransactionManager' Create a transaction that we'll abort
  Dim tr As Transaction
  Set tr = tm.StartTransaction(doc, "Temp")' You should not leave a transaction' hanging in the air. It will make Inventor' unstable. So in case of error we'll' skip to aborting the whole thing
  On Error GoTo Oops
  Dim tro As TransientObjects
  Set tro = ThisApplication.TransientObjects
  Dim p As Profile
  Set p = sk.Profiles.AddForSolid()
  Dim coll As ObjectCollection
  Set coll = tro.CreateObjectCollection' If there is a single outermost loop' then that should be the first one
  Dim pp As ProfilePath
  Set pp = p(1)
  Dim pe As ProfileEntity
  For Each pe In pp
    Call coll.Add(pe.SketchEntity)
  Next
Oops:
  Call tr.Abort
  If Err <> 0 Then Exit Sub' Let's select the lines in the UI
  Call doc.SelectSet.SelectMultiple(coll)
End Sub

Here are pics showing the results:

Sketchprofile

 

Execute vs Execute2 of ControlDefinition

$
0
0

By Adam Nagy

This blog post's Command Execution Behavior section already talks about this but might be worth mentioning it again and providing some more details.

There are three ways to run an existing command: Execute, Execute2(Synchronous=False) and Execute2(Synchronous=True).

If we ran the same command that was also used in the other article in three different ways then we would observe the following behaviour:

Sub TestControlDefinitionExecute()
  Dim cm As CommandManager
  Set cm = ThisApplication.CommandManager
  Dim cds As ControlDefinitions
  Set cds = cm.ControlDefinitions
  Dim cd As ControlDefinition
  Set cd = cds("AssemblyPlaceComponentCmd")
  Debug.Print "Before Execute"
  Call cd.Execute'Call cd.Execute2(False)'Call cd.Execute2(True)
  Debug.Print "After Execute"
End Sub

Execute
So Execute2(Synchronous=False) is fully asynchronous, it does not wait for dialogs either, whereas Execute() does, and only returns once the dialog got dismissed. Execute2(Synchronous=True) is fully synchronous as it waits for the command to finish completely.
In case of commands (e.g. AppFileOpenCmd) which show a dialog but have no interactive bits like moving a component around in the document view, the Execute() and Execute2(True) functions return at the same time, right after the dialog got dismissed. 

Reuse Inventor UI components

$
0
0

By Adam Nagy

You may want to create command dialogs or palettes that look just like Inventor's, e.g. like the one the Extrude command has.
Unfortunately, there is no direct way to do that; Inventor API does not provide a way to reuse components or customize existing dialogs.
Also, the icons being used are spread across different resource dll's so it could be difficult to find them. The easiest way to create a dialog similar to an Inventor command's is to get a screenshot of the UI that you are interested in and then recreate from that the png's needed for your buttons. 

There is a sample in the SDK that does that: "C:\Users\Public\Documents\Autodesk\Inventor 2015\SDK\DeveloperTools\Samples\VCSharp.NET\AddIns\CustomCommand"

I have updated it to use the latest UI look, inc. making the entity selection button's arrow white once the selection has been accomplished, use png's instead of ico's, and added a nice command icon as well -  Download CustomCommand2015

Rackface
 

 

Align DrawingView to Face and Edge

$
0
0

By Adam Nagy

Wrote a few articles on drawing views already, but they do not seem to be enough :)

http://adndevblog.typepad.com/manufacturing/2014/11/rotate-drawing-view-around-x-axis-of-sheet.html 
http://adndevblog.typepad.com/manufacturing/2014/11/rotate-camera-around-any-axis-any-angle.html 
http://adndevblog.typepad.com/manufacturing/2014/11/drawing-coordinate-systems-and-camera.html 

So, now here is one on aligning the view to show a given face. To make this work directly in a drawing, where only edges can be selected, we'll let the user select two drawing curve segments. From those we'll find the corresponding model edges, and then we'll find the common face of those edges. Using the Face's normal we'll set the camera's view direction, and using the second selected Edge's direction we'll set the UpVector of the view.
Note that the below code only works with planar faces and linear edges, and the direction of the edge used to set the UpVector may be opposite to what you'd like in which case the view will be upside-down.

Function GetFace(edges() As Edge) As Face
  Dim i As Integer
  Dim j As Integer
  For i = 1 To 2
    For j = 1 To 2
      If edges(0).Faces(i) Is edges(1).Faces(j) Then
        Set GetFace = edges(0).Faces(i)
        Exit Function
      End If
    Next
  Next
End Function

Sub SetViewDirection()
  Dim doc As DrawingDocument
  Set doc = ThisApplication.ActiveDocument

  Dim edges(1) As Edge
  Set edges(0) = doc.SelectSet(1).Parent.ModelGeometry
  Set edges(1) = doc.SelectSet(2).Parent.ModelGeometry
  
  Dim f As Face
  Set f = GetFace(edges)
  
  Dim p As Plane
  Set p = f.Geometry
  
  Dim dv As DrawingView
  Set dv = doc.SelectSet(1).Parent.Parent
  
  Dim c As Camera
  Set c = dv.Camera
    
  ' Set Eye or Target
  Dim pt As Point
  If f.IsParamReversed Then
    Set pt = c.Eye.Copy
    Call pt.TranslateBy(p.Normal.AsVector())
    c.Target = pt
  Else
    Set pt = c.Target.Copy
    Call pt.TranslateBy(p.Normal.AsVector())
    c.Eye = pt
  End If' Set UpVector
  Dim ls As LineSegment
  Set ls = edges(1).Geometry
  c.UpVector = ls.Direction
  Call c.ApplyWithoutTransition
End Sub

Here is the result:

Drawingview
 

 

Show VBA dialog from Ribbon

$
0
0

By Adam Nagy

Anything that shows in the Macros dialog can also be hooked up to a new Ribbon button: http://adndevblog.typepad.com/manufacturing/2015/01/userform-function-not-listed-in-macros-dialog.html

There are two types of functions:
- Sub: that does not return a value
- Function: that returns a value and so its declaration
                   ends with an "As <object type>", e.g.:

Public Function GetMeAString() As String
  GetMeAString = "Some string"
End Function

In the Macros dialog only Sub's will show up as running a macro does not require a result. The Customize dialog also only shows Sub's, but also only the ones from the Default VBA project - the one set here:

VBA1

Inside the Customize dialog you can narrow down the search to Macros to make it easier to find and then place it on any of the Ribbon tabs: 

VBA2

In order for our form to pop up when the button on the Ribbon is clicked we have to set things up the same way as it was done in the other blog post:

Public myForm As UserForm1

Public Sub MySub()
  Set myForm = New UserForm1
  myForm.Show
End Sub

The way you can edit your form should be the same in all VBA environments, like the one in Excel, so you can find other resources on that on the web, e.g. https://msdn.microsoft.com/en-us/library/office/aa192538(v=office.11).aspx 

Not able to recognize add-in in the path with non-English chars

$
0
0

By Xiaodong Liang

 

I got one case last week, in which it is reported that Inventor cannot recognize one add-in if the binary (dll) is deployed to a path that contains non-English chars. e.g. the *.addin file is:

<?xml version="1.0" encoding="utf-8"?>

……
<DisplayName>VBNetRibbonDemo</DisplayName>
<Description>VBNetRibbonDemo</Description>
<Assembly>C:\temp\新建文件夹\VBNetRibbonDemo.dll</Assembly>

Where新建文件夹 is a Chinese string. As you can see, the file header has specified xml with utf-8, however it does not help.

I scratched my head, however did not get a clue what the problem is. And I beleieved both the customer and I have missed something, otherwise, many developers who are working with non-English add-in would have complained.

I had to ask help of engineer team. When one engineer opened my *.addin file at his side, the Chinese chars are messy. I suddenly realized what my problem is.

I opened the *.addin and added Chinese chars by notepad and simply saved the file, while it is ANSI format!. After switching to utf-8 and saving again, it can also work at my side now!

The customer is running the vbscript file to create the addin file. There may be something wrong in creating the *.addin file. thus the file does not tell the correct chars to Inventor.

I am writing down this issue for your reference.

image

Cannot extrude sketch geometry

$
0
0

By Adam Nagy

You may have created sketch curves that overlap, but their end points do not meet, so you cannot extrude the area they enclose. Actually, the end points of the curves do not need to coincide in order to be recognised as a profile; it's enough if the curves are tied together with points - i.e. there is a point that is constrained to be coincident with both curves.

So if you start with something like this:

Sketch1

Then you can use the following VBA code to solve the problem:

Public Sub AddSketchPoints()' You need to be in Sketch environment
  Dim sk As PlanarSketch
  Set sk = ThisApplication.ActiveEditObject' This expects to have the sketch' entities shown in the picture:' straight lines on each side connected' by arcs
  Dim lines As SketchLines
  Set lines = sk.SketchLines
  Dim arcs As SketchArcs
  Set arcs = sk.SketchArcs' Create 4 points and constrain each to' a line and an arc
  Dim pts As SketchPoints
  Set pts = sk.SketchPoints
  Dim gc As GeometricConstraints
  Set gc = sk.GeometricConstraints
  Dim line As SketchLine
  Dim arc As SketchArc
  For Each line In lines
    For Each arc In arcs' Temporarily fix the line and arc so' they do not move around
      Dim gnd(1) As GroundConstraint
      Set gnd(0) = gc.AddGround(line)
      Set gnd(1) = gc.AddGround(arc)' Does not matter where we place' it initially
      Dim pt As SketchPoint
      Set pt = pts.Add(line.StartSketchPoint.Geometry)' Now constrain it to a line' and an arc
      Call gc.AddCoincident(arc, pt)
      Call gc.AddCoincident(line, pt)' Delete the temporary constraints
      Call gnd(0).Delete
      Call gnd(1).Delete
    Next
  Next
End Sub

Sketch2

Now this can be extruded:

Sketch3

 


Drive Rule in Sub Sheet Metal part to Export DWG/DXF by DataIO

$
0
0

By Xiaodong Liang

These days, I got one case, where one assembly includes some sheet metal parts. In each part, there are some rules, one of which exports the document to DWG/DXF, another exports to other file format. In the assembly, one rule iterates each parts and executes the rules.

It works well with other format. i.e. after running rule of assembly, the corresponding files are generated. But DWG/DXF are not generated. An unspecific error occurred. If activating the parts one by one and run the assembly rule again, the DWG/DXF files can be generated now.

I did a couple of test and found the problem is because of the way of exporting. For other format, the rule uses TranslatorAddin, while for DWG/DXF, the rule uses SheetMetalComponentDefinition.DataIO.WriteDataToFile
while it requires to in the editing mode of sheet metal: SheetMetalComponentDefinition.FlatPattern.Edit.
The code failed at FlatPattern.Edit. It looks if the sheet metal part has not been explicitly activated or opened, the flat pattern mode cannot be edited.

Finally, the workaround is to activate the components one by one (like activate manually) before running the rule will edit the flat pattern.

This is the test assembly and part: Download TestData

The relevant rules are as below:

assembly rule:

 
'for the rule that will edit flat pattern, 
' activate the parts in advance

DimoAssDocAsAssemblyDocumentoAssDoc=ThisApplication.ActiveDocument
DimoAssDefAsAssemblyComponentDefinitionoAssDef=oAssDoc.ComponentDefinition
DimoCompAsComponentOccurrence
For Each oComp In oAssDef.Occurrences   
    oComp.Edit()
 
  
oComp.ExitEdit(ExitTypeEnum.kExitToTop)
Next

DimopenDocAsDocumentopenDoc=ThisDoc.Document
DimdocFileAsDocument

'if this is an assembly document
If openDoc.DocumentType=    DocumentTypeEnum.kAssemblyDocumentObject Then

    For EachdocFile In openDoc.AllReferencedDocuments

        Dim FNamePos As Long
        FNamePos=InStrRev(docFile.FullFileName, "\", -1)                               

        Dim docFName As String  
        
docFName=Right(docFile.FullFileName,
    Len(docFile.FullFileName)-FNamePos

        'drive the sub rule   
        iLogicVb.RunRule(docFName, "exportDWG_DXF_ByDataIO")    
     Next

Else
    MessageBox.Show("This is not an assembly document", "Error")
End If 

sheet metal part rule: 

Dim curDoc=ThisDoc.Document 

'if this is a sheet metal part
If curDoc.SubType="{9C464203-9BAE-11D3-8BAD-0060B0CE6BB4}" Then      

    Dim oCompDef As SheetMetalComponentDefinition   
   oCompDef=curDoc.ComponentDefinition

    'edit the flat pattern   
   oCompDef.FlatPattern.Edit
    

    Dim sOut As String   
    Dim sPATH As String
   
    sPATH=ThisDoc.Path

    DimsFnameAsString 

    sOut="FLAT PATTERN DWG?AcadVersion=2004
&RebaseGeometry=True
&OuterProfileLayer=DIGI_CUTTING_TOOL_2
&OuterProfileLayerColor=102;102;102
&InteriorProfilesLayer=DIGI_CUTTING_TOOL_1
&InteriorProfilesLayerColor=255;255;255
&BendDownLayer=DIGI_MARKER_TOOL_2
&BendDownLayerColor=255;127;223
&BendUpLayer=DIGI_MARKER_TOOL_1
&BendUpLayerColor=0;255;0
&InvisibleLayers=IV_ARC_CENTERS;IV_TANGENT;IV_ROLL;IV_ROLL_TANGENT;IV_ALTREP_BACK;IV_ALTREP_FRONT;
IV_FEATURE_PROFILES_DOWN;IV_FEATURE_PROFILES;IV_TOOL_CENTER_DOWN"
  
    sFname=

  sPATH&"\"&ThisDoc.FileName(False)&".dwg"    

    'sOut = "FLAT PATTERN DXF?AcadVersion=R12&OuterProfileLayer=Outer"   
  'sFname = sPATH & "\" & ThisDoc.FileName(False) & ".dxf"
 

    oCompDef.DataIO.WriteDataToFile(sOut, sFname

    oCompDef.FlatPattern.ExitEdit   

Else

     MessageBox.Show("This is not a sheet metal part!","Error"

EndIf

 

Transform imported geometry

$
0
0

By Adam Nagy

When importing geometry from another CAD format like *.step then you cannot specify the transformation for it in the UI. The only thing you can do is transform the geometry in another part document derived from the one that has the imported geometry.
However, using Brian's solution you can achieve that through the API directly in the part document that has the imported geometry. It also takes care of keeping the look of the component the same by copying the Appearance of the original faces:

Public Sub ReorientBaseBody()
  Dim partDoc As PartDocument
  Set partDoc = ThisApplication.ActiveDocument
  Dim pcd As PartComponentDefinition
  Set pcd = partDoc.ComponentDefinition
  Dim npbfs As NonParametricBaseFeatures
  Set npbfs = pcd.Features.NonParametricBaseFeatures' Get the base feature that was created as a result of ' the translation.
  Dim baseFeature As NonParametricBaseFeature
  Set baseFeature = npbfs(1)' Get the body created by the translation.
  Dim originalBody As SurfaceBody
  Set originalBody = baseFeature.InputSurfaceBodies(1)' Create a transient copy of the body.
  Dim newBody As SurfaceBody
  Set newBody = ThisApplication.TransientBRep.Copy(originalBody)

  Dim tg As TransientGeometry
  Set tg = ThisApplication.TransientGeometry
 
  Dim tr As TransientObjects
  Set tr = ThisApplication.TransientObjects

  ' Define the transform to apply to the body.
  Dim trans As Matrix
  Set trans = tg.CreateMatrix
  Call trans.SetCoordinateSystem( _
    tg.CreatePoint(2, 2, 2), tg.CreateVector(0, 1, 0), _
    tg.CreateVector(-1, 0, 0), tg.CreateVector(0, 0, 1))' Apply the transform to the transient body.
  Call ThisApplication.TransientBRep.Transform(newBody, trans)' Create a new base feature.
  Dim baseFeatureDef As NonParametricBaseFeatureDefinition
  Set baseFeatureDef = npbfs.CreateDefinition()
  Dim inputBodies As ObjectCollection
  Set inputBodies = tr.CreateObjectCollection
  Call inputBodies.Add(newBody)
  baseFeatureDef.BRepEntities = inputBodies
  baseFeatureDef.OutputType = kSolidOutputType
  Dim newFeature As NonParametricBaseFeature
  Set newFeature = npbfs.AddByDefinition(baseFeatureDef)

  Dim realBody As SurfaceBody
  Set realBody = newFeature.SurfaceBodies(1)

  Dim i As Integer
  For i = 1 To originalBody.Faces.count
    Dim originalFace As Face
    Set originalFace = originalBody.Faces(i)
    
    If originalFace.AppearanceSourceType = kOverrideAppearance Then
      Dim newFace As Face
      Set newFace = realBody.Faces(i)
        
      newFace.Appearance = originalFace.Appearance
    End If
  Next

  ' Delete the original feature.
  baseFeature.Delete
End Sub

Transform

 

List suppressed components in LOD

$
0
0

By Adam Nagy

When a given LOD (Level Of Detail) is active inside Inventor that simply means that you are looking at a specific document inside the file: each LOD is a separate document stored inside the same file - see File vs Document 

If you want to list which components are suppressed inside a given LOD - not the one currently active in the UI - then you don't have to activate it just for that. You can simply open that LODdocument in the background, check which components are suppressed, then close the document if it's not the currently active LOD:

Sub ListWhatsSuppressed()
  Dim asm As AssemblyDocument
  Set asm = ThisApplication.ActiveDocument
  Dim acd As AssemblyComponentDefinition
  Set acd = asm.ComponentDefinition
  Dim rm As RepresentationsManager
  Set rm = acd.RepresentationsManager
  Dim nvm As NameValueMap
  Set nvm = ThisApplication.TransientObjects.CreateNameValueMap()
  Dim doc As AssemblyDocument
  Dim occ As ComponentOccurrence
  Dim lod As LevelOfDetailRepresentation
  For Each lod In rm.LevelOfDetailRepresentations
    Debug.Print lod.name
    Call nvm.Add("LevelOfDetailRepresentation", lod.name)
    Set doc = ThisApplication.Documents.OpenWithOptions( _
      asm.FullFileName, nvm, False)
    Call nvm.Clear
    For Each occ In doc.ComponentDefinition.Occurrences
      Debug.Print " >> " + occ.name + _" Suppressed = " + Str(occ.Suppressed)
    Next' Don't forget to close the document not used anymore
    If Not lod Is rm.ActiveLevelOfDetailRepresentation Then
      Call doc.Close(True)
    End If
  Next
End Sub

In this document I added two of my own LOD's as well: one has Combo Assembly, the other has Catch Post component suppressed:

Suppressed

The above VBA code gives the following result:

Master>> Combo Assembly:1 Suppressed = False>> Catch Post:1 Suppressed = False>> Lock Shackle:1 Suppressed = False>> Case Inner:1 Suppressed = False>> Case Outer:1 Suppressed = False>> Case Back:1 Suppressed = False>> Dial:1 Suppressed = False>> Catch Assembly:1 Suppressed = False>> Catch:2 Suppressed = False>> Retainer:1 Suppressed = False
All Components Suppressed>> Combo Assembly:1 Suppressed = True>> Catch Post:1 Suppressed = True>> Lock Shackle:1 Suppressed = True>> Case Inner:1 Suppressed = True>> Case Outer:1 Suppressed = True>> Case Back:1 Suppressed = True>> Dial:1 Suppressed = True>> Catch Assembly:1 Suppressed = True>> Catch:2 Suppressed = True>> Retainer:1 Suppressed = True
All Parts Suppressed>> Combo Assembly:1 Suppressed = False>> Catch Post:1 Suppressed = True>> Lock Shackle:1 Suppressed = True>> Case Inner:1 Suppressed = True>> Case Outer:1 Suppressed = True>> Case Back:1 Suppressed = True>> Dial:1 Suppressed = True>> Catch Assembly:1 Suppressed = False>> Catch:2 Suppressed = True>> Retainer:1 Suppressed = True
All Content Center Suppressed>> Combo Assembly:1 Suppressed = False>> Catch Post:1 Suppressed = False>> Lock Shackle:1 Suppressed = False>> Case Inner:1 Suppressed = False>> Case Outer:1 Suppressed = False>> Case Back:1 Suppressed = False>> Dial:1 Suppressed = False>> Catch Assembly:1 Suppressed = False>> Catch:2 Suppressed = False>> Retainer:1 Suppressed = False
ComboSuppressed>> Combo Assembly:1 Suppressed = True>> Catch Post:1 Suppressed = False>> Lock Shackle:1 Suppressed = False>> Case Inner:1 Suppressed = False>> Case Outer:1 Suppressed = False>> Case Back:1 Suppressed = False>> Dial:1 Suppressed = False>> Catch Assembly:1 Suppressed = False>> Catch:2 Suppressed = False>> Retainer:1 Suppressed = False
CatchSuppressed>> Combo Assembly:1 Suppressed = False>> Catch Post:1 Suppressed = True>> Lock Shackle:1 Suppressed = False>> Case Inner:1 Suppressed = False>> Case Outer:1 Suppressed = False>> Case Back:1 Suppressed = False>> Dial:1 Suppressed = False>> Catch Assembly:1 Suppressed = False>> Catch:2 Suppressed = False>> Retainer:1 Suppressed = False

Upcoming Fusion 360 API Webinar

$
0
0

FusionWebinar

Are you using Fusion 360 or just curious about it?  It’s API is still relatively new and is growing significantly with each frequent release.  This webinar will discuss the programming capabilities of Fusion, including the new Add-In functionality that is coming and will be available by the Webinar.

The webinar is on March 25 at 9:00 AM Pacific time.  To attend the webinar, please register for Get started with Fusion 360 API at:

https://attendee.gotowebinar.com/register/7034449259570533633

After registering, you will receive a confirmation email containing information about joining the webinar.

-Brian

Delete suppressed components in iLogic

$
0
0

By Adam Nagy

I have written a blog post on this topic and provided VBA code. If you want to convert it to iLogic then first of all you need to have a basic understanding of iLogic. Going through the help could be a good start.

Then, one by one, try to resolve the error messages given by the iLogic editor.

Here is the iLogic version of the VBA code:

Sub Main()
    Dim doc As AssemblyDocument
    doc = ThisApplication.ActiveDocument
    Dim acd As AssemblyComponentDefinition
    acd = doc.ComponentDefinition
    Call DeleteSuppressedComponent(acd.Occurrences)
End Sub

Sub DeleteSuppressedComponent(occs As ComponentOccurrences)
  Dim occ As ComponentOccurrence
  For Each occ In occs
    If occ.Suppressed Then
      occ.Delete
    Else
      Call DeleteSuppressedComponent(occ.SubOccurrences)
    End If
  Next
End Sub
Viewing all 519 articles
Browse latest View live