Thursday, September 18, 2014

Inserting a UDF (User Defined Feature) programatically in CREO by using a VB Application

In this example we are to use the box of the last exercise, be sure this box has minimum 300mm length, 100mm Depth and 150mm height (or larger for the 3 dimensions)
The UDF we are to create will ask for the user to select a coordinate System  on a surface, and also the user can enter the X and Y distance to this coordinate system. The Reference coordinate system should have the Z vector pointing out normal to the surface. Follow next steps for creating the UDF.
Create a reference coordinate system for the UDF (This CS will not be included in the UDF


Orient with Z axis pointing normal to the surface, X lengthwise and Y crosswise

Create another coordinate system (This CS WILL be included in the UDF definition) referenced on the previous CS and with the offset shown in the image below (20 in X direction and 20 in Y direction)

Now let’s proceed with the creation of the hole feature; select extrude

Select the ‘placement’ tab

Click on ‘Define…’ button

Click on plane textbox

Now we are to create “on the fly” references, click in Model Tab and in “Plane”, as is shown in the image below

Select Z and 0 as the offset direction and dimension, click okay

Now repeat the process for the refernce datum plane, click the “Reference” textbox

And again select Datum plane and click on the CS Select X and 0 as the offset direction and dimension, click okay

Select in the “sketch” dialog box, Right orientation for the reference datum plane and click okay,

Now select the CS as the reference, delete all other references

Make a circle as shown below, the center is constrained in the reference, click okay

Make the extrude a cut and “trough all” option for the depth as shown below, click okay to the extrude creation

Now select the “Tools tab” and “UDF Library”

Next dialog box menu appears in the right top corner

Select “create” and type “Hole01” for the UDF name and click okay


Select Stand alone

And click ‘NO’ to the dialog box asking for including the reference part

Next dialog box appears asking for adding features

Select in the model tree the Coordinate system and the extrude (The last 2 created features)

Click okay and done, then for the prompts type “Reference Coordinate System”

Go to the ‘Var Dims’ Option in the UDF definition dialog and select the Coordinate Sytem (CS1 in this example), all dimensions highlight as shown in the image below

Select the X and Y dimensions that position the CS (CS1) in the surface

The prompt for the values will be X Dimension an Y dimension as shown below, click okay and the definition of our UDF is ready.

Insert the UDF
For testing the previous definition, let’s insert the UDF we have already created.
Select the User-Defined Feature command in the Model tab as shown below

Next dialog box will appear, be sure all options are set as in the image (Advanced reference configuration), and click okay

Next dialog box appears, click on the ‘Reference otf the UDF Features’ textbox, and select the reference coordinate system, remember that the z axis of the CS should be normal to the surface where hol will be inserted, in this case select CS0 as the reference, next picture shows it

Click on the variables tab of the dialog box and type 60 for X dimension and 0 for Y dimension as in next picture and click okay.

The UDF is working so the screen should look similar to this image

Now let’s do this automatically from a VB application
By using MS Visual Studio, add text boxes to the form as is shown below, set the default values also

Create a new class and name it as: “Public Class pfcFeaturesExamples” as shown below


Imports pfcls

Public Class pfcFeaturesExamples
    'Create Hole UDF In Part
    '======================================================================
    'Function   :   createHoleUDFInPart
    'Purpose    :   This function places copies of a node UDF at a
    '               particular coordinate system location in a part. The
    '               node UDF is a cylinder cut centered at the coordinate
    '               system whose diameter is driven by the argument to the
    '               method. The method returns the Feature Group object
    '               created.   
    '======================================================================
    Public Function createHoleUDFInPart(ByVal placementModel As IpfcSolid, _
                                        ByVal Name01 As String, _
                                        ByVal csysName As String, _
                                        ByVal Dim1 As Double, _
                                        ByVal Dim2 As Double) _
                                        As IpfcFeatureGroup

        Dim csys As IpfcCoordSystem = Nothing
        Dim cSystems As IpfcModelItems
        Dim i As Integer
        Dim udfInstructions As IpfcUDFCustomCreateInstructions
        Dim csysSelection As IpfcSelection
        Dim csysReference As IpfcUDFReference
        Dim references As CpfcUDFReferences
        Dim variantDims As IpfcUDFVariantDimension
        Dim variantDims2 As IpfcUDFVariantDimension
        Dim variantVals As IpfcUDFVariantValues
        Dim group As IpfcFeatureGroup

        Try

            cSystems = placementModel.ListItems(EpfcModelItemType.EpfcITEM_COORD_SYS)

            For i = 0 To cSystems.Count - 1
                If (cSystems.Item(i).GetName.ToString = csysName) Then
                    csys = cSystems.Item(i)
                    Exit For
                End If
            Next

            If csys Is Nothing Then
                Throw New Exception("Coordinate System not found in current Solid")
            End If

            '======================================================================
            'Instructions for UDF creation
            '======================================================================
            udfInstructions = (New CCpfcUDFCustomCreateInstructions).Create(Name01)

            '======================================================================
            'Make non variant dimensions blank to disable their display
            '======================================================================
            udfInstructions.DimDisplayType = EpfcUDFDimensionDisplayType.EpfcUDFDISPLAY_BLANK

            '======================================================================
            'Initialize the UDF reference and assign it to the instructions. 
            'The string argument is the reference prompt for the particular
            'reference.
            '======================================================================
            csysSelection = (New CMpfcSelect).CreateModelItemSelection(csys, Nothing)

            csysReference = (New CCpfcUDFReference).Create("Reference Coordinate System", csysSelection)

            references = New CpfcUDFReferences
            references.Set(0, csysReference)

            udfInstructions.References = references

            '======================================================================
            'Initialize the variant dimension and assign it to the instructions.
            'The string argument is the dimension symbol for the variant dimension.
            '======================================================================          
            variantDims = (New CCpfcUDFVariantDimension).Create("d6", Dim1)
            variantDims2 = (New CCpfcUDFVariantDimension).Create("d7", Dim2)
            variantVals = New CpfcUDFVariantValues
            variantVals.Set(0, variantDims)
            variantVals.Set(1, variantDims2)


            udfInstructions.VariantValues = variantVals

            '======================================================================
            'We need the placement model for the UDF for the call to
            'CreateUDFGroup(). If you were placing the UDF in a model other than
            'the owner of the coordinate system, the placement would need to be
            'provided separately.
            '======================================================================

            group = placementModel.CreateUDFGroup(udfInstructions)

            Return group

        Catch ex As Exception
            MsgBox(ex.Message.ToString + Chr(13) + ex.StackTrace.ToString)
            Return Nothing
        End Try
    End Function
End Class

Go back to the form and on the ‘on click’ event of the “Insert UDF” Button add the next code:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim asyncConnection As IpfcAsyncConnection = Nothing
        Dim run As New pfcFeaturesExamples
        Dim Model As IpfcModel
        Dim Solid As IpfcSolid

        Try
            asyncConnection = (New CCpfcAsyncConnection).Connect(Nothing, Nothing, Nothing, Nothing)
            Model = asyncConnection.Session.CurrentModel
            If Model Is Nothing Then
                Throw New Exception("Model not present")

            End If
            If (Not Model.Type = EpfcModelType.EpfcMDL_PART) And _
                (Not Model.Type = EpfcModelType.EpfcMDL_ASSEMBLY) Then
                Throw New Exception("Model is not a solid")
            End If
            Solid = CType(Model, IpfcSolid)
            run.createHoleUDFInPart(Solid, TextBox5.Text, TextBox4.Text, TextBox7.Text, TextBox8.Text)
            MsgBox("Hole Created")
        Catch ex As Exception
            MsgBox(ex.Message.ToString + Chr(13) + ex.StackTrace.ToString)
        End Try
    End Sub

In this case the name of the textboxes is as follow in the picture:


Test the form and the UDF should be inserted in the model.
____________
TRADEMARKS: Creo, Pro/ENGINEER, Pro/Toolkit, J-Link, Pro/Web.Link, Pro/Program and VB API are registered trademarks of PTC (http://www.ptc.com/). All other products or services mentioned in this blog are the trademarks or service marks of their respective companies or organizations.

Tuesday, February 11, 2014

Basic Setup: a way to increase productivity

                    
In order to increase productivity, it is not necessary to use the complex capabilities of the program, just by taking advantage of a proper set up and doing the modelling in the right manner there could be huge savings.                                   
                                              
Next will be the default settings:                              
- Millimeters as the default unit for all models.                                  
- Default Datum planes will be named as: Longitudinal, Horizontal and transversal           
- Template will have some basic parameters for creating BOMs in a more automated way                                 
Also this template should have an evaluate feature that will maintain the information of the dimension of the parts.                                  
A basic setup will allow the creation of multi-language BOMs                               
                                              
Part Template  
                               
Create a folder in the windows explorer where all template files will be stored. Then from ProE set this folder as the working directory                  
Create a new part                 
Name it as: template_part_01                      
Uncheck the 'use default template' option               
Click OK                    
Select 'empty' as template and click OK                 
A part file with an empty tree appears                     
Add a datum plane and automatically 3 are created                      
Rename them as: Horizontal, Longitudinal and Transverse                       
Add a coordinate system also, select the 3 planes for origin positioning and select Longitudinal plane as the normal for Z, transverse as the normal for X and Horizontal as the normal plane for Y.              
Change units of the system by selecting: File>Setup>model properties. A dialog box must appear and set as follows:                      
Select Material 'steel' because for our examples we will use normally mild steel 
Select Units and set 'mmKgSeg' in this case units will be millimeters, force in kilograms force and time in seconds           
Close the dialog box  
Now insert a feature for measuring entities. This is a feature that will allow us to measure dimensions for a plate automatically             
Select  Insert>model Datum>evaluate…    
Name the feature as: MDIM 
Create a measure parameter named L (for length)
Select 'Distance' and 'Plane' select the transverse plane and next again select 'Plane' and the transverse plane           
Create another measure parameter named W (for Width), in this case select Longitudinal plane           
Create one another measure parameter named T (for Thickness), in this case select Horizontal plane 
Check the status of the parameters just by selecting 'info' and should appear something similar to the image below.           
Click 'Done'   
Now add a relation for showing the measure parameters in the normal parameters                    
This relation should be added in the relations of part. Select tools>relations and a dialog box should appear     
Next snippet will assign measure parameters to regular parameters:        
/*** EVALUATE FEATURE ""MDIM"" EXTRACT DIMENSION FROM THE MODEL
/***  REORDER TO THE END OF THE FEATURE LIST
/***  REDEFINE AND REDO THE REQUIRE PARAMETERS
/* T=T:FID_MDIM
/* L=L:FID_MDIM
/* W=W:FID_MDIM"
Next one will create a new parameter named 'dimension' for keeping the string that will appear in the BOM    
/***  SET PARAMETER DIMENSION FOR BOM (PART LIST)
/*** PLATE, SHEET, FLAT OR SQUARE BARS, L-PROFILE
IF FLOOR(T)==T
    DIMENSION = ITOS(T)+""X""+ITOS(W)+""X""+ITOS(L)
 ELSE
    DIMENSION=ITOS(FLOOR(T))+"",""+ITOS((T-FLOOR(T))*10)+\
    ""X""+ITOS(W)+""X""+ITOS(L)
 ENDIF"
Next picture shows the dialog box with the code above explained, also you can check the variables    
Click OK        
Some other important variables will be defined as follows:            
ID: is a string that will be the identifier of the part    
DESCRIPTION: a string that have a text that describes the part (i.e. Support, bracket, etc.)     
DESCRIPTION_SP: a string that have a text that describes the part in spanish language          
DESCRIPTION_GE: a string with description in german language           
PREPARED: name of the person responsible for the design        
APPROVED: name of the person reviewing the design     
MASS: is a real number that will have the calculated mass of the part and will be assigned in a relation.          
Next commented relations can be used when necessary. 
/*MP_DENSITY=MASS_AUX/MP_VOLUME("""")
/*MASS=MP_MASS("""")"
Of course more information can be added to the template because this info will be used afterwards for creating BOMS automatically and the idea is this information to be generated automatically just by changing parameters in an upper structure.                
In this case and for our example this information is enough.                     
Save and close

Testing the Part template
                     
For testing our template, let's do next steps:           
Create a new part     
Name it as: testing_part        
Uncheck the 'use default template' option   
Click OK        
Select 'template_part_01' as template and click OK (look for the template in the working directory)     
The new part will 'inherit' all the setup we prepared in the template part.   
Create a protrusion as a box
Drag the MDIM feature and drop after the extrude feature you've just created, click on MDIM feature and right click mouse, next select 'edit definition'    
A redefine dialog box appears at right of the screen           
Be sure the references option is checked and then click on 'Done'           
Then the 'Measure parameters' dialog box appears on the left, select the 'redo' option   
Choose 'L' and redefine it as the distance between the 2 planes of the box in the longitudinal direction 
Choose 'W' and redefine it as the distance between the 2 planes of the box in the transversal direction
Choose 'T' and redefine it as the distance between the 2 planes of the box in the vertical direction       
Click done     
Regenerate the part  
Change the dimensions of the box to: 300mm Length, 220mm Width and 10mm Thickness     
Regenerate the part  
Open the parameters dialog box: tools>parameters and check the values (L,W,T,Dimension) are those you assigned to the extrude feature        
Change dimensions, regenerate and check accordingly in the parameters box.  
Save the part 

Assembly template                           

Create a new assembly                    
Name it as: template_assy_01                     
Uncheck the 'use default template' option               
Click OK                    
Select 'empty' as template and click OK                 
An assembly file with an empty tree appears (you should click settings>tree filters and select features for viewing features in the assembly's model tree)                    
Add a datum plane and automatically 3 are created                      
Rename them as: Horizontal, Longitudinal and Transverse                       
Add a coordinate system also, select the 3 planes for origin positioning and select Longitudinal plane as the normal for Z, transverse as the normal for X and Horizontal as the normal plane for Y.              
Change units of the system by selecting: File>Setup>model properties. A dialog box mut appear and set as follows:                       
Select Units and set 'mmKgSeg' in this case units will be millimeters, force in kilograms force and time in seconds           
Close the dialog box  
Some other important variables will be defined as follows:            
ID: is a string that will be the identifier of the part    
DESCRIPTION: a string that have a text that describes the part (i.e. Support, bracket, etc.)     
DESCRIPTION_SP: a string that have a text that describes the part in spanish language          
DESCRIPTION_GE: a string with description in german language           
PREPARED: name of the person responsible for the design        
APPROVED: name of the person reviewing the design     
MASS: is a real number that will have the calculated mass of the part and will be assigned in a relation.          
Next commented relations can be used when necessary. 
/*MASS=MP_MASS("")
Of course more information can be added to the template because this info will be used afterwards for creating BOMS automatically and the idea is this information to be generated automatically just by changing parameters in an upper structure.                
In this case and for our example this information is enough.                     
Save and close      

Testing the Assembly template
               
For testing our template, let's do next steps:           
Create a new assembly        
Name it as: testing_assy       
Uncheck the 'use default template' option   
Click OK        
Select 'template_assy_01' as template and click OK (look for the template in the working directory)    
The new part will 'inherit' all the setup we prepared in the template part.   
Save the part 

These templates defined here are very simple but you can create more complex ones. For example if you usually create paralelepipeds, a protrusion can be included in the template part or assembly, with the preferred material and units already setup.  

Thanks.              

Monday, February 10, 2014

Controlling a Box in CREO from MSExcel by using the VB API

Once the setup up part was finished, we are ready to test this API. In this simple example we are to use the capabilities for parameters the API has. In other exercise we will show something more sophisticated but based fundamentally in the very same ability of CREO for controlling a model via parameters.

The Box

Let's make in CREO a part with the name "box.prt", in it create a solid box with 3 dimensions (Length, Depth and Height).






Then Create 3 parameters for the 3 dimensions above mentioned. Let's name the variables as: LENGTH, DEPTH and HEIGHT





Now, in the "relations" dialog box, relate each parameter with the dimensions in the box





So we are ready from the side of CREO.

The Excel Side

Now on the side of Excel, let's create a new spreadsheet. and format it as is shown in next picture



Let's take advantage of the validation capabilities of Excel for restricting user inputs and avoid incorrect data to be passed to CREO API. So make the 3 dimensions to be more than 10 units and less than 800 units (let's say mm or inches). Also of course The values should be numeric. Next Image shows how it should look like when trying to enter a vale lower than 10 for HEIGHT Parameter.



Add a Button for connecting to CREO,



and insert the next snippet of code in the on-click event(This code allows for you to update the LENGTH from excel, DEPTH and HEIGHT are not updated as you can see in the code lines):

Private Sub UpdateCreo_Click()

Dim asyncConnection As IpfcAsyncConnection
Dim cAC As CCpfcAsyncConnection
Dim session As IpfcBaseSession
Dim model1 As IpfcModel
Dim px As IpfcParameterOwner
Dim p01, p02 As String
Dim p1 As IpfcParameter
Dim p2 As IpfcBaseParameter
Dim Mitem As CMpfcModelItem
Dim pv1 As IpfcParamValue

p01 = "LENGTH"
Range("D5").Select
p02 = ActiveCell.Text

Set cAC = New CCpfcAsyncConnection
Set asyncConnection = cAC.Connect(dbnull, dbnull, dbnull, dbnull)
Set session = asyncConnection.session
Set model1 = session.GetModel("BOX.PRT", EpfcMDL_PART)
Set px = model1
Set p1 = px.GetParam(p01)
Set p2 = p1
Set Mitem = New CMpfcModelItem
Set pv1 = Mitem.CreateDoubleParamValue(CDbl(p02))
p2.Value = pv1

asyncConnection.Disconnect (1)

End Sub


Test the button and this will allow you to update the box's LENGTH from Excel by using the VB API for PTC's CREO.

Thanks.