SNAP and NX Open For GRIP Enthusiasts: Version 10: October 2 2014
SNAP and NX Open For GRIP Enthusiasts: Version 10: October 2 2014
for
GRIP Enthusiasts
© 2014 Siemens Product Lifecycle Management Software Inc. All rights reserved.
Table of Contents
1. Introduction ....................................................... 1 13. Curves ............................................................... 30
Background........................................................................................ 1 Lines ................................................................................................... 30
The Programming Tools Decision ........................................... 1 Arcs and Circles ............................................................................. 31
Prerequisites ..................................................................................... 1 Conic Sections ................................................................................ 31
Using this Document ..................................................................... 1 Splines ............................................................................................... 31
Isoparametric Curves ................................................................. 32
2. Some Basic Differences ................................... 2 Offset Curves .................................................................................. 32
Language Versus Library............................................................. 2 Edge Curves .................................................................................... 32
WCS versus ACS ............................................................................... 3 Curve Evaluator Functions....................................................... 32
Strong versus Weak Typing ....................................................... 3
Points and Positions ...................................................................... 3 14. Surfaces ............................................................ 33
Error Handling ................................................................................. 3 Legacy Surfaces ............................................................................. 33
Analytic Surfaces .......................................................................... 34
3. Creating a Program .......................................... 4 Bounded Plane ............................................................................... 34
Creating a Source File ................................................................... 4 Plane ................................................................................................... 34
The Benefits of an IDE .................................................................. 4 B-Surface .......................................................................................... 35
Compiling............................................................................................ 5 Surface Evaluator Functions ................................................... 35
Linking ................................................................................................. 5
Running a Program ........................................................................ 5 15. Simple Features ............................................. 35
Debugging........................................................................................... 5 Primitive Features ....................................................................... 36
An Example Program .................................................................... 6 Extruded and Revolved Features .......................................... 36
Create Tube Feature.................................................................... 36
4. Variables and Declarations ............................ 7 Create Prism ................................................................................... 36
Statements ......................................................................................... 7 Using NX Open Builders ............................................................ 36
Lines of Code ..................................................................................... 7
Comments........................................................................................... 7 16. Body Operations............................................ 37
Data Types.......................................................................................... 8 Joining Operations ....................................................................... 37
Declarations ...................................................................................... 8 Blending and Chamfering ......................................................... 37
Using Imports Statements .......................................................... 8 Cutting and Splitting ................................................................... 38
Making Declarations Optional................................................... 9
Variable Names ................................................................................ 9 17. Drawings & Annotations ............................ 38
Numbers.............................................................................................. 9 Drawings .......................................................................................... 38
Strings ............................................................................................... 10 Dimensions...................................................................................... 39
Object Variables ............................................................................ 10 Notes .................................................................................................. 40
Arrays ................................................................................................ 10 18. Layers & Categories...................................... 41
Arithmetic Expressions ............................................................. 11 Layers ................................................................................................ 41
Array Expressions ....................................................................... 11
String Expressions ....................................................................... 12 19. Attributes ........................................................ 41
Boolean Expressions .................................................................. 13 Assigning Attributes.................................................................... 41
Deleting Attributes ...................................................................... 42
5. Math Functions ................................................ 14 Reading Attribute Values .......................................................... 42
6. Programming Constructs ............................. 15 20. General Object Properties ......................... 43
Statement Labels .......................................................................... 15 General Properties ....................................................................... 43
Unconditional Branching.......................................................... 15 Object Types ................................................................................... 43
Conditional Branching ............................................................... 15 General Functions ........................................................................ 44
Looping ............................................................................................. 15 Transformations ........................................................................... 44
Simple Logical IF .......................................................................... 16
Block IF ............................................................................................. 16 21. Analysis/Computation Functions ............ 45
Arithmetic IF .................................................................................. 16 Distances Between Objects ...................................................... 45
Subroutines .................................................................................... 16 Deviation .......................................................................................... 45
Arclength .......................................................................................... 45
7. The SNAP Architecture .................................. 18 Area and Volumetric Properties ............................................ 46
Object vs. Function Names....................................................... 18
Object Properties ......................................................................... 19 22. CAM ................................................................... 46
Cycling Through CAM Objects ................................................ 46
8. User Interaction .............................................. 19 Editing CAM Objects .................................................................... 48
CHOOSE — Choosing One Item from a Menu ................. 20 CAM Views ....................................................................................... 49
MCHOOS — Choosing Several Items from a Menu ....... 20 Creating a Tool............................................................................... 50
PARAM and TEXT — Entering Numbers and Text ....... 20
GPOS and POS — Specifying Positions ............................... 21 23. Global Parameters ........................................ 51
DENT — Selecting Objects ....................................................... 21
Writing Output .............................................................................. 23 24. File Operations .............................................. 51
File Operations .............................................................................. 51
9. Database Access .............................................. 23 Directory Cycling .......................................................................... 51
Cycling Through a Part .............................................................. 23 File Information GPAs ................................................................ 52
Cycling Through a Body ............................................................ 24
25. Working with Text Files .............................. 53
10. Expressions..................................................... 24 Reading ............................................................................................. 53
Writing .............................................................................................. 54
11. Positions, Vectors, and Points ................... 25
Positions........................................................................................... 25 26. Operating System Interaction ................... 54
Vectors .............................................................................................. 26 Environment Variables .............................................................. 54
Points ................................................................................................. 28 Running Another Process ......................................................... 55
Point Sets ......................................................................................... 28
27. New Opportunities ....................................... 55
12. Coordinate Systems ...................................... 29
Mapping Between Coordinate Systems ............................. 29 28. Getting Further Help .................................... 56
1. Introduction
Background
Historically, the GRIP language has been a very popular tool for extending and personalizing NX. Writing simple
GRIP programs is fairly easy, so many NX users are able to create small utility functions that significantly enhance
their productivity. But GRIP has not been enhanced for many years, so some GRIP users are thinking about adopting
more modern solutions like SNAP or NX Open. This document is intended to help, by showing you how you can use
SNAP or NX Open to do things that you might have done with GRIP in the past.
In most cases, we will guide you towards using SNAP, rather than NX Open, since SNAP is simpler, and closer to
GRIP in spirit and syntax. But SNAP does not have drafting or CAM functions, yet, so we’ll (briefly) tell you how to
use NX Open functions in these areas. You can freely mix calls to SNAP functions and calls to NX Open functions, so
using the two tools together works smoothly.
Prerequisites
To make good use of this document, you certainly don’t need to be an expert GRIP programmer, but we assume that
you have some familiarity with NX, and with the parts of the GRIP language that you have used in the past. You don’t
need to be an expert in Visual Basic or SNAP, or NX Open, either, but we assume that you have a little prior
knowledge. You can learn all you need to know by skimming through the first four chapters of the SNAP Getting
Started Guide, which will likely take an hour or two.
GRIP is a language. SNAP and NX Open are libraries of functions. You can call these
functions from any .NET language. The SNAP documentation
focuses on the Visual Basic (VB) language, but you can use other
languages, like C#, if you prefer.
GRIP programs only make sense in the VB programs can be used for a huge variety of purposes, most of
context of NX which are unrelated to NX
GRIP has its own special syntax, its own With SNAP, you use the standard VB language and compiler, and
compiler, and its own development tools standard development tools like Visual Studio or your favorite
text editor.
In a GRIP program, a typical line of code uses In a VB program that uses SNAP, a typical line of code calls a
a GRIP “statement” to perform some action SNAP function to perform some action (like creating an NX
(like creating an NX object) object).
So, for example, the GRIP language includes a The SNAP library includes a function named Spline, which you
SPLINE/ statement, which creates a spline can call from your VB code. Again, it creates a spline curve, just
curve. like the SPLINE/ statement in GRIP.
The GRIP code on the left would work; the VB code on the right would cause an error. In fact, you would probably
receive a warning in the middle of typing the third line of code.
Points are permanent. Once created, a Point Positions are temporary. Once your SNAP program has finished
will remain in the NX database (unless you executing, the Position objects that it used no longer exist.
delete it, of course).
If a Point is only needed temporarily, you will You don’t need to explicitly delete Positions. They simply “die”
need to delete it after using it. when they are no longer in use.
Error Handling
Many GRIP statements include an IFERR minor word that allows you to jump to some specified statement in case of
an error. In VB, a different approach is used, known as “structured exception handling”. Certain SNAP functions will
“throw” an exception if they encounter an error situation internally. This means that control will immediately
return to the calling code (i.e. your code), which must then decide how to handle the exception. You handle
exceptions by enclosing any error-prone code in standard VB Try/Catch blocks.
A GRIP source file is just a plain text file, so A VB program that calls SNAP functions is again just a plain text
you can create it using any text editor. file, so you could create it using a standard text editor if you
wanted. But it’s usually much more convenient to use the NX
Journal Editor or a specialized programming tool like Visual
Studio.
A GRIP source file has the .GRS extension A VB source file has the .VB extension.
The two different ways of writing SNAP programs are described in detail in the SNAP Getting Started guide.
Chapter 2 covers the NX Journal Editor, and Chapter 3 tells you how to install and use Visual Studio.
Function
Completion documentation
suggestions
Intellisense dramatically reduces your typing burden, and eliminates many syntax errors. Enthusiasts like to say
that “the code writes itself”. This isn’t true, or course, but the benefits are certainly very significant.
To compile a GRIP source file, you use the When using the NX Journal Editor, there is no explicit “compile”
“compile” option in the GRADE step. You simply choose the “run” command, and the compilation
environment. The compilation step step is performed in the background.
produces “object” files with the .GRI
In Visual Studio, you compile your code using the “Build”
extension.
command (press Ctrl+Shift+B).
Linking
The third step of GRIP program development is to link previously generated object files into an executable module.
To link a GRIP program, you use the “link” option in VB programs do not require linking. The compilation step
the GRADE environment. The linking step produces produces an executable program directly.
an executable program.
A GRIP executable file has the .GRX extension A VB executable file can have either .EXE or .DLL as its
extension.
Running a Program
Once you have an executable program, you will want to run it, of course.
To run a GRIP program from within NX, you use To run a SNAP or NX Open program from within NX, you
File Execute GRIP (or press Ctrl+G). use File Execute NX Open (or press Ctrl+U).
Of course, once you have a working program, you'll probably want a more convenient way of running it. You might
assign it to a menu or a toolbar button, for example. This is possible regardless of whether your program was
written using GRIP, SNAP, or NX Open.
Debugging
If your program does not execute as expected, you will need to debug it.
To debug a GRIP program, choose There are no debugging facilities in the NX Journal Editor.
File Execute Debug GRIP
Visual Studio has a broad range of debugging tools. You can set
breakpoints, step through the code one line at a time, examine the
values of variables, and so on. Many tutorials describing Visual Studio
debugging techniques are available on the internet.
As you can see, the code that does the real work (creating lines and arcs) looks roughly the same in both GRIP and
VB, but the VB code has a bit more “framework” around it. To mimic the GRIP code as closely as possible, the VB
code shown here uses an array of NX.NXObject variables, but this is not a typical practice, as we will see later.
It might be interesting to run the VB code, to see what happens. The simplest way to do this is to copy/paste it from
this document into the NX Journal Editor. In NX, press Alt+F11 to get a new journal file, delete whatever text it
contains, if any, and paste in the text from the right-hand cell above. To run the program, just click on the large red
arrow on the right-hand end of the Journal Editor’s toolbar:
Statements
A GRIP program consists primarily of “statements”, which are roughly equivalent to function calls in main-stream
programming languages. In many cases, the statements or function calls create new objects in an NX part file
A GRIP statement typically consists of a major word, An analogous line of code in a VB program would consist
followed by a “slash”, and then perhaps some minor of a call to a function. The function might be from the
words. SNAP library, or from some other standard library, or it
might be a function that you wrote yourself.
For example, consider the statement The analogous VB code using a SNAP function is
myLine = LINE/1,3,4,2,7,9 myLine = Line(1,3,4,2,7,9)
This creates a line between the locations (1,3,4) and Again, this creates a line between the locations (1,3,4)
(2,7,9) and assigns this to the variable “myLine”. and (2,7,9) and assigns it to the variable “myLine”.
Subsequently, you could delete this line by writing Subsequently, you could delete this line by writing
DELETE/myLine Delete(myLine)
Lines of Code
A statement usually fits on one line. But when it is too long, you can continue it onto the next line by placing a
“continuation indicator” at the end of the first line.
In GRIP, the continuation indicator is $ In VB, the continuation indicator is a space followed by an
underscore
Actually, in modern versions of Visual Basic, the underscores are often unnecessary, since the compiler can figure
out by itself when a line of code is supposed to be a continuation of the one before it.
Also, in VB, you can actually place multiple statements on a single line if you separate them by the colon (:)
character.
Comments
Comments are descriptive text to help readers understand the code. They are ignored by the compiler.
In GRIP, a comment is preceded by $$, and it In VB, a comment is preceded by ' (a single quote), and it
extends to the end of the line. extends to the end of the line.
NUMBER Integer The available data types in GRIP, and a few of the common built-in
ENTITY Double ones in VB.
STRING Char
String
Boolean
Object
There are many other built-in data types in VB, including byte, decimal, date, and so on, but the ones shown above
are the most useful for our purposes. For more details of the available built-in data types, please see Chapter 4 of
the SNAP Getting Started Guide, or one of the many books and on-line tutorials covering the VB language. Actually,
VB allows you to define new custom data types of your own, so the number of types is essentially unlimited. SNAP
and NX Open introduce hundreds of custom types, including things like Snap.NX.Point, Snap.Vector, NXOpen.Arc, and
so on.
Declarations
In many programming languages, you must “declare” variables before you use them. The declaration tells the
compiler what type of variable you want, and how much space should be reserved for it.
In GRIP, all the declarations must appear at the In VB code, you can declare variables anywhere. The most
beginning of your program common practice is to declare them immediately before their
first use, often in the same line of code.
In GRIP, you write ENTITY/ to declare any NX In VB programs, you typically declare objects of specific
object, regardless of what type it is types, rather than using broad types like Snap.NX.NXObject.
ENTITY/LN1,LN2,A1 Dim line1, line2 As Snap.NX.Line Declare two lines and an arc.
Dim a1 As Snap.NX.Arc
So, declaring variables requires a bit more work in VB. But this extra work is worthwhile in the long run, because it
gives you variables that are strongly typed, and this allows the compiler to find many of your mistakes immediately,
as explained in section 2.
GRIPSW/DECLRV Option Explicit On Tells the compiler to warn you when it finds undeclared
variables
Option Infer On Tells the VB compiler to try to guess the types of variables
(which reduces the effort of declaring them)
Please refer to a VB tutorial or to Chapter 4 of the SNAP Getting Started guide for more information about the
Explicit and Infer options.
Variable Names
Regardless of their types, there are some rules for forming legal variable names in GRIP and VB.
GRIP variable names cannot exceed 32 characters In VB, there is no limit on the length of a variable name
Only the first 6 characters are significant, so they All the characters in the variable name are significant
must be unique
The first character must be a letter The first character must be a letter or an underscore
As you can see, any variable name that’s legal in GRIP is also legal in VB. So, if you rewrite a GRIP program in VB,
you can keep all the old variable names, which might be helpful.
Numbers
GRIP has only a single numerical data type, called NUMBER. VB has several numerical types, but the most common
are Integer and Double, which have the following properties.
Integer A positive or negative whole number in the range –2,147,483,648 through 2,147,483,647
Double A floating-point number in the range 4.9 × 10–324 to 1.8 × 10308, positive or negative
Variables of type Double can be expressed using scientific notation such as 3.56E+2. The “E” refers to a power of 10,
so 3.56E+2 means 3.56 × 102, which is 356, and 3.56E-2 means 0.0356.
Here are some examples of declarations of numerical variables:
In GRIP, a sequence of characters is declared using the In VB, a sequence of characters is declared as a String
STRING/ declaration, like this: variable, like this:
STRING/name(10) Dim name As String
Literal strings are enclosed in single quotes: Literal strings are enclosed in double quotes:
name = 'John Smith' name = "John Smith"
Notice that when you declare a string in GRIP, you have to specify how many characters it will contain. There is no
need to do this in VB. Some further examples of string declarations are:
Object Variables
In GRIP, we use an ENTITY variable to represent any NX object. The analogous type in SNAP is an NX.NXObject
variable. However, VB also has an Object type, which can represent anything at all, including things that are
completely unrelated to NX. Rather than using these very general types, it is usually better to use more specific
ones, like NX.Line or NX.Arc, because this helps the compiler to identify mistakes in your code.
In GRIP, NX object variables must be declared using In VB, the closest equivalent is the NX.NXObject data
the ENTITY/ declaration. type. However, it is better to use specific data types like
NX.Line or NX.Spline.
A GRIP ENTITY variable can only contain NX objects A VB “Object” variable can hold anything at all (related
like splines and solid bodies. to NX or not)
Arrays
In addition to “simple” variables, you can declare arrays of variables of any type. An array is just a collection of
items that are related to each other in some way, and have the same data type. You can then use the array as a single
object in subsequent operations. Within an array, you can refer to an individual element by using the name of the
array plus a number, called the array “index”.
STRING/fruits(2,6) Dim fruits(1) As String In GRIP, we have to specify the size of the two
fruits(1) = 'Apple' fruits(0) = "Apple" string variables. Since the second string has 6
fruits(2) = 'Banana' fruits(1) = "Banana" characters, we have to use a size of 6. In VB, we do
not have to specify the sizes of the two strings, and
in fact they can have different sizes.
Arrays can be multi-dimensional. In fact, in VB, an array can have up to 32 dimensions, though it is rare to use more
than three dimensions.
GRIP provides the DATA keyword, which allows you assign initial values to variables after declaring them. In VB, it is
common to declare and initialize a variable in a single line of code, as shown in the examples below. If you declare
and initialize an array this way, then you do not need to specify its size, because the compiler can determine this
from the initialization.
Arithmetic Expressions
Arithmetic operators are used to perform the familiar numerical calculations on variables of type Integer and
Double. The only operator that might be slightly unexpected is the one that performs exponentiation (raises a
number to a power).
Array Expressions
Array expressions provide a convenient method of performing addition or subtraction operations on arrays, or of
setting one array equal to another. Using an array expression is the same as performing the operation on each
individual element of the array.
String Expressions
A string expression is a combination of two or more input strings.
Strings are combined using the “+” operator Strings are combined using the “&” operator
There are many GRIP functions that manipulate character strings. The SNAP library has very few functions of this
type because they are provided by Visual Basic and the .NET framework, instead.
In the following tables, s, s1, s2, s3 denote strings, c is a character, n1 and n2 are integers, and x is a floating-point
number (typically a Double).
DATE and TIME DateTime.Now( ) Return the current date and time as strings
Boolean Expressions
A boolean variable is one whose value is either “true” or “false”. In GRIP, boolean variables or expressions cannot
exist as stand-alone objects, they have to be embedded in “IF” or “BLOCKIF” statements, which are described a little
later. In VB, boolean variables behave in more-or-less the same way as other types of variables — you can declare
them, combine them in expressions, assign values to them, and so on.
The VB code could have been written in much the same way as the GRIP code, without the positive and small
variables. We could have just written If (x>0) And (x*x < 200) Then state = "OK". But using separate boolean variables,
as shown, often makes the code easier to read.
In VB, boolean variables can be combined using logical operators, as follows:
And: the result is True when both of the operands are True
Or: the result is True when at least one of the operands is True
Not: this is a unary operator. The result is True if the operand is False
Xor: the result is True when exactly one of the operands is True
Only the last of these (the Xor operator) is different from GRIP.
True/false values often arise from equality/inequality comparisons of numbers or strings, as in the following:
Note that GRIP uses “==”for equality comparison, but VB just uses “=”.
Other useful functions in VB include the hyperbolic functions (Sinh, Cosh, Tanh), Log10, Round, PI, and others. Visual
Studio Intellisense will show you a complete list as you type.
The System.Math class also contains all the usual trigonometric functions, so you can write things like:
Note that the trigonometric functions in the System.Math class expect angles to be measured in radians, not in
degrees. In SNAP, angles are always expressed in degrees, not in radians, since this is more natural for most people.
So, SNAP has its own set of trigonometric functions (SinD, CosD, TanD, AsinD, AcosD, AtanD, Atan2D) that use degrees,
instead.
If you have Imports Snap.Math at the top of your file, then the code from above can be written more clearly as:
The following table lists the trigonometric functions in the Snap.Math class:
Statement Labels
A label is a name that may precede any GRIP statement (except for the PROC statement). The label provides a way
for other code to reference a place in your program. The label is followed by a colon. VB has exactly the same
mechanism, though it is used much less frequently
zeroK: K = 0 zeroK: K = 0 A line of code that sets K equal to zero, and which
has the label “zeroK”
Unconditional Branching
The GRIP JUMP/ statement allows you to perform unconditional branching, which causes the program to branch to
the statement containing the specified label. This type of branching uses the GoTo keyword in VB. While
unconditional branching can certainly be handy, at times, its use is generally frowned upon in modern
programming, since it can easily lead to incomprehensible “spaghetti” code.
Conditional Branching
Another form of the JUMP/ statement causes the program to branch to one of several locations based on an integer
value. The closest analog in VB is a Select Case construct. This is not really the same thing, but it sometimes can
serve a similar purpose.
Looping
The DO/ statement provides a way to perform a given set of operations a specified number of times. The
corresponding construct in VB is the For/Next loop.
Note that you do not have to provide a label for the end of the loop in VB; you always use Next for this purpose. In
VB, there are other loop constructs, such as the While loop, the Do loop, and the For Each loop.
Block IF
The block IFTHEN/ statements allow you to conditionally execute blocks (or groups) of GRIP statements. Again, VB
has an almost identical construct:
Arithmetic IF
The IF/ statement provides multi-choice branching based on the value of a numerical variable. There is no
corresponding construct in VB.
Subroutines
A function or subroutine gathers together a block of code that performs some well-defined function that you may be
able to re-use in several different places. By placing code in a subroutine, rather than repeating it, you can improve
the organization of your code and make it easier to understand, maintain, and share.
You pass inputs to a function when you call it, the code inside the function is executed, and then (sometimes) a
value is returned to you as output. VB distinguishes between a function that returns a value to its caller and one
that doesn't. The former is called a “Function”, and the latter is called a “Subroutine”, or just “Sub”.
In GRIP, you place each subroutine in a separate .GRS file, with the PROC keyword in the first line. Then, to invoke
the subroutine, you use the CALL keyword along with the name of the file in which the subroutine resides. In VB, all
functions have to belong to a “class” or “module”, but you can organize them into files however you like. VB
functions have individual names, which are independent of the names of the files in which they are defined.
The general pattern for a function definition in VB is:
So, the definition of a typical function named CircleArea might look like this:
The first line indicates that the following code (up until the End Function line) defines a function called CircleArea
that receives a Double as input and returns a Double as output.
As you can see, the name of the function is given in the first line of its definition, so you don't have to put every
function in its own file, as you do in GRIP. Also, note that it’s perfectly legal to have several functions with the same
name, provided they have different types of inputs. This technique is called “overloading”, and the function name is
said to be “overloaded”. For example, the function name “Average” is overloaded in the list of function definitions
above. When you call the function, the compiler will decide which overload to call by looking at the types of inputs
you provide.
To call the functions described above, you write code like the following:
Functions in VB can have optional arguments, and there are some special techniques for handling arrays as function
arguments. Both techniques are used quite often in SNAP, so it's worth knowing about them. Please refer to
chapter 4 of the SNAP Getting Started guide for details.
You don't need to understand everything in this diagram; we just want to point out a few important things.
Object Properties
The objects in the Snap.NX namespace have rich sets of properties that you can use to get information about them.
You almost always use these properties, rather than “Get” or “Ask” functions. For example, if circ is a Snap.NX.Arc
object, its radius is circ.Radius, not circ.GetRadius or circ.AskRadius. In many cases, properties are also writable, so
you can use them to modify an object. Using properties rather than Get/Set functions cuts the number of functions
in half, and makes your code more readable. The concept will be familiar to you if you have used EDA (Entity Data
Access) symbols in GRIP.
8. User Interaction
The user interface of NX has changed dramatically since the days when GRIP was created. The GRIP statements for
creating user interfaces still work, but they produce results that look rather out-of-place in modern versions of NX.
Since around 2007, the NX user interface has been based on “block-based” dialogs, so-called because they are built
from a common collection of user interface “blocks”. So, for example, the following dialog consists of four blocks,
whose types are indicated by the labels to the right
Enumeration block
Integer block
Action Button block
String block
Each block has a specific type and purpose. So, looking at the four examples from the dialog above:
An Enumeration block presents a set of options to the user, and asks him to choose one of them
An Integer block allows the user to enter an integer (by typing, or by using a slider, for example)
An Action Button block performs some action when the user clicks on it
A String block displays text that the user can (sometimes) edit
There are several different ways to construct these “block-based” dialogs in SNAP, as described in chapters 12
though 14 of the SNAP Getting Started guide. The simplest functions (in the Snap.UI.Input class) are described in
chapter 12, and more sophisticated techniques using BlockForms and BlockDialogs are covered in chapter 13 and
chapter 14. The discussion below will help you make connections between GRIP statements and the analogous
SNAP techniques.
The “style” argument allows you to indicate how you want the choices displayed, as shown in the pictures below.
The two options are radio buttons (shown on the left), or a pull-down option menu (on the right):
Alternatively, you can construct a BlockForm or a BlockDialog that contains a block of type “Enumeration”.
Or, you can construct a BlockForm or a BlockDialog that contains a block of type “ListBox”.
The GetDouble function provides very similar capabilities, for entering double (floating point) numbers, and the
GetString function allows entry of a string of text. Also, there are similar functions called GetIntegers, GetDoubles,
and GetStrings, which let you enter several items of data, rather than just one.
Alternatively, to construct more complex dialogs, you may use a BlockForm or a BlockDialog containing blocks of
type Integer, Double, or String.
Similarly, the Snap.UI.Input.GetVector function lets the user specify a vector, and Snap.UI.Input.GetPlane lets the user
specify a plane.
To construct more complex dialogs, you may use a BlockForm or a BlockDialog containing blocks of type
SpecifyPoint, SpecifyVector, SpecifyPlane, SpecifyCursorLocation, SpecifyOrientation, and so on.
dialog.SetFilter(NX.ObjectTypes.Type.Line)
dialog.Title = "Selection Demo"
dialog.Scope = Selection.Dialog.SelectionScope.AnyInAssembly
dialog.IncludeFeatures = False
When the code shown above is executed, a small dialog appears allowing the user to select a line.
If the user selects a line and clicks OK, the selected line will be available to your code in the Selection.Result object,
so you can do whatever you want with it. In the example above, we chose to make the line hidden (blanked).
Alternatively, you might want to support selection inside a larger block-based dialog, rather than using a standalone
selection dialog. To do this, one option is to place a SelectObject block on a BlockForm, like this:
dialog.AddBlocks(selectionBlock)
When this code is executed, a small dialog appears, giving the user the opportunity to select a line:
If the user selects a line and clicks OK, the line will be hidden (blanked).
In either case (whether you use a stand-alone selection dialog or selection block), all the standard NX selection
techniques are supported. This includes chain selection, so there is no need for a specific replacement for the GRIP
CHAIN/ statement.
produces the following display, which says “Arigato” (Japanese for “thank you”)
You can also write output to text files; this is covered later, in section 25.
9. Database Access
It is often useful to cycle through an NX model and performing certain operations on some subset of the objects
found. GRIP uses the INEXTE and NEXTE statements to cycle through general objects, and the INEXTN and NEXTN
statements to cycle through non-geometric ones.
10. Expressions
An Expression consists of an “equation” that has three parts, each of which is a string:
The “Name” — the portion before the equals sign (i.e. the left-hand side)
The “RightHandSide” — the portion after the equals sign but before the comment
The “Comment” — the portion following the characters “//”, up until the end of the equation
So, for example, if the entire equation is
myExp.Equation = xxx
EXPEDT/ myExp.Name = xxx Edit expressions
myExp.Value = xxx
Positions
A Position object represents a location in 3D space. You can use the following functions to create a Position:
These functions are all constructors, so, when calling them, we have to use the “New” keyword in our code. Here are
some examples:
Dim p As New Position(3,5,8) ' Creates a position "p" with coordinates (3,5,8)
Dim q As New Position(1.7, 2.9) ' Creates a position "q" with coordinates (1.7, 2.9, 0)
Dim w As Double() = { 3, 5, 8 } ' Creates an array of three numbers
Dim z As New Position(w) ' Creates a position from the array
Dim p, q As Position
Dim point As New NXOpen.Point3d(3, 4, 5)
Dim coords As Double( ) = {6, 7, 8}
p = point ' Implicit conversion -- no explicit conversion required
q = coords ' Implicit conversion -- no explicit conversion required
This conversion facility provides a very nice way of defining Position objects; you can write things like:
Note that the PolarTheta and PolarPhi angles are returned in degrees, not radians, as is standard in SNAP.
Positions are very important objects in CAD/CAM/CAE, so they receive special treatment in SNAP. To make our
code shorter and easier to understand, many Position functions have been implemented as operators, which means
we can use normal arithmetic operations (like +, −, *) instead of calling functions to operate on them. So, if u, v, w
are Positions, then we can write code like this:
As you can see from the first line of code above, addition and scalar multiplication of Positions is considered to be
legal. In fact, only certain types of expressions like this make sense, but we have no good way to distinguish
between the proper ones and the improper ones, so we allow all of them.
Vectors
A Snap.Vector object represents a direction or a displacement in 3D space. You can use the following constructor
functions to create Vector objects:
SNAP can implicitly convert an array of three doubles or an NXOpen.Vector3d object into a Vector, so again we do not
have to perform casts, and we can define vectors conveniently using triples of numbers:
The GRIP and SNAP functions for doing computations with vectors are:
SNAP also has a UnitCross function whose output is a unitized cross product.
In SNAP, you can also scale a vector by using a division operation. So, if v is a vector, then you can write u = v/2 to get
a vector that's half of v.
SNAP also provides three built-in unit vectors called AxisX, AxisY, AxisZ corresponding to the coordinate axes.
Vector object properties are as follows:
Double PolarPhi get Angle between the vector and the XY-plane, in degrees
Again, many Vector functions have been implemented as operators, which means we can use normal arithmetic
operations (like +, −, *) instead of calling functions to operate on them. So, if p and q are Positions, u, v, w are
Vectors, and r is a “scalar” (an Integer or a Double), then we can write code like this:
For more information about Vector objects, please refer to the SNAP Reference Guide.
As always, the coordinates input to the SNAP function should be relative to the Absolute Coordinate System. The
properties of Point objects are as follows:
SNAP functions often require Positions as inputs. If we have a Point, instead of a Position, we can always get a
Position by using the Position property of the point. So, if myPoint is a Point, and we want to create a sphere (which
requires a Position for the center) we can write:
Sphere(myPoint.Position, radius)
Since their X, Y, Z properties can be set (written), it’s easy to move points around, as follows:
p1 = Point(1, 2, 5)
p2 = Point(6, 8, 0)
p1.Z = 0 ' Projects p1 to the xy plane
p1.Y = p2.Y ' Aligns p1 and p2 –- gives them the same y-coordinate
The code above assumes that we have Imports Snap.Create at the top of our file. Without this, we would have to
write p1 = Snap.Create.Point(1,2,5) and so on.
Point Sets
The GRIP Point Set (CPSET) statements create collections of point objects spaced along existing curves or faces. The
corresponding SNAP functions are the Curve.PositionArray and Face.PositionArray functions. The SNAP functions
return arrays of Position objects, rather than creating points:
The GRIP CPSET command also allows creation of points at the control vertices (poles) of splines and b-surfaces. In
SNAP, we can use the Poles properties to access poles:
Of the three, Orientations are the most heavily used in SNAP. You can think of an Orientation either as a rotation
matrix (a 3×3 matrix with determinant = 1), or as a set of three mutually orthogonal unit vectors forming a “frame”.
The three vectors can be obtained by using the AxisX, AxisY and AxisZ properties of the orientation.
Many SNAP objects have an Orientation property. A few also have AxisX, AxisY and AxisZ properties, which provide a
shortcut, allowing you to get these three vectors from the object itself, rather than from its Orientation.
&XAXIS(myArc) myArc.AxisX Get the local x-axis vector of an arc (either directly
myArc.Orientation.AxisX from the arc, or indirectly from its Orientation)
GRIP uses CoordinateSystem objects quite extensively, but in SNAP it is more common to use an Orientation, instead.
Once you have created an Orientation in SNAP, you can then create a CoordinateSystem, if you want to, though this
second step is often unnecessary.
The Work Coordinate System (WCS) is represented in SNAP by the Snap.Globals.Wcs property, which is equivalent to
the GRIP &WCS GPA. Also, the orientation of the WCS is represented by the Snap.Globals.WcsOrientation property.
You can use either of these two properties to set the WCS or obtain information about it.
csys = &WCS csys = Snap.Globals.Wcs Get the coordinate system of the WCS
13. Curves
Lines
The Snap.Create class contains several functions for creating lines:
The following fragment of code creates two points and two lines in your Work Part:
Notice how z-coordinates can be omitted, in some cases. Since it’s quite common to create curves in the xy plane,
we provide special shortcut functions for doing this, so that you don’t have to keep typing zeros for z-coordinates.
The properties of lines are:
The StartPoint and EndPoint properties can be set, so you can use them to edit a line, like this:
Dim myLine As NX.Line = Line(2,3,7,8) ' Creates a line between (2,3,,0) and (7,8,0)
myLine.EndPoint = {7,8,5} ' Moves the end-point to (7,8,5)
The NX.Line class also inherits some useful properties from NX.Curve, such as Arclength:
In several cases, the SNAP functions receive an orientation as an input, which allows you to orient the arc/circle
however you like in 3D space.
The following snippet of code uses lines and arcs to create the shape shown on the right:
SNAP also has Fillet functions, which again create Snap.NX.Arc objects:
Conic Sections
SNAP has functions for creating ellipses, but to create parabolas or hyperbolas you must use NX Open functions,
instead.
Alternatively, you can use SNAP spline functions to create curves that are shaped exactly like parabolas or
hyperbolas, even though they are actually Snap.NX.Spline objects.
Splines
GRIP has both SPLINE and BCURVE statements, which primarily support creation of splines passing through a given
sequence of points. In SNAP, the Snap.Create.SplineThroughPoints functions provides similar capabilities. For the
special case of a Bezier curve (a spline with only a single segment), SNAP provides a specific
BezierCurveThroughPoints function.
With the VERT minor word, the GRIP BCURVE command also allows you to create a spline from given control vertices
(poles). Similar capabilities are provided by the SNAP Spline and BezierCurve functions:
The SNAP functions are somewhat more flexible, since they allow you to specify b-spline weights and nodes.
The Snap.Math.SplineMath class provides some lower-level tools for use by people who are spline experts.
Isoparametric Curves
In SNAP, the functions that create isoparametric belong to individual face classes, so that they can return curves of
specific known types. For example, the Cylinder.IsoCurveU function returns lines, and the Cylinder.IsoCurveV function
returns arcs.
Offset Curves
The GRIP and SNAP functions are:
Edge Curves
GRIP provides the SOLEDG function to create curves corresponding to edges. In SNAP, this operation is typically not
necessary, because SNAP functions work uniformly on either curves or edges. In fact, many SNAP functions receive
an object called an ICurve as input, and an ICurve can be either a curve or an edge. But, if you really want to create
curves that replicate edges, SNAP provides Edge.ToCurve and similar functions
14. Surfaces
GRIP was created long before NX supported solid and sheet bodies. In those days, much of the 3D work in NX was
performed using what we called “surfaces”. The GRIP “surface” commands are still supported. Using today's
terminology, they create sheet bodies that have only a single face.
The bodies created are “dumb” orphans, rather than associative features; they retain no links to their parent
objects. By contrast, most of the analogous SNAP functions create feature objects. If this is not what you want, you
can always use the Orphan function to disconnect the object from its parents.
Legacy Surfaces
GRIP has commands to create the “surfaces” that were the primary 3D modeling objects in ancient times. These
include surfaces of revolution, tabulated cylinders, ruled surfaces, fillet surfaces, sculptured surfaces, and offset
surfaces. The commands are REVSRF, TABCYL, and so on. The corresponding SNAP functions are outlined below:
REVSRF/ Revolve( ) The GRIP command creates a “surface of revolution”, which is an orphan
RevolveSheet( ) sheet body with a single face. The SNAP functions both create NX.Revolve
features
TABCYL/ Extrude( ) A “Tabulated Cylinder” is an extruded sheet body with a single face.
ExtrudeSheet( ) The SNAP functions both create NX.Extrude features
RLDSRF/ Ruled( ) The GRIP command produces a sheet body having a single face of type
b-surface. The SNAP function creates an NX.Ruled feature.
FILSRF/ EdgeBlend( ) GRIP produces a sheet body having a single face of type b-surface.
FaceBlend( ) The SNAP functions create EdgeBlend and FaceBlend features.
SSURF/ ThroughCurveMesh( ) The GRIP command produces a sheet body having a single b-surface face.
The SNAP function creates an NX.ThroughCurveMesh feature.
OFFSRF/ OffsetFace( ) The GRIP command produces a sheet body having a single face.
Thicken( ) The SNAP functions create features.
CYLNDR/ ExtrudeSheet( ) The GRIP function creates a sheet body with a single cylindrical face. The
RevolveSheet( ) SNAP functions create features of various types.
EdgeBlend( )
Cylinder( )
CONE/ ExtrudeSheet( ) The GRIP function creates a sheet body with a single conical face.
RevolveSheet( ) The SNAP functions create features of various types.
Cone( )
SPHERE/ RevolveSheet( ) The GRIP function creates a sheet body with a single spherical face. The
EdgeBlend( ) SNAP functions create features of various types.
Sphere( )
Bounded Plane
The GRIP BPLANE command creates a planar sheet body bordered by a given collection of curves. The closest
corresponding SNAP function is Snap.Create.BoundedPlane.
In both cases, a collection of curves is provided as input. In the SNAP command, these curves can be in any order,
and it is not necessary to indicate which of them define interior holes.
Plane
The GRIP PLANE command creates a plane object. Plane objects are infinite in extent, and do not form part of a body.
They are typically used as reference objects — for example a plane might be used for mirroring, or to specify the
location of a cross-section.
In SNAP, there are two corresponding objects: Snap.NX.DatumPlane, and Snap.Geom.Surface.Plane. A Datum Plane
serves roughly the same purpose as a plane object, but Datum Planes are features that are linked to their parent
objects. A Geom.Surface.Plane is a non-persistent object that is not stored in an NX model and exists only within a
SNAP program. In SNAP, each curve has a Plane property which gives the plane containing the curve (if the curve is
planar).
If you really want to create the same kind of object as the GRIP PLANE command, you should use the NX Open
function NXOpen.UF.UFModl.CreatePlane
The GRIP BSURF command also allows surfaces to be built from collections of curves, using techniques that are
similar to those provided by the SNAP ThroughCurves and ThroughCurveMesh functions:
The GRIP functions each create a “dumb” sheet body with a single b-surface face. The SNAP functions create
features.
Again, as with curve evaluators, parameters are not normalized to the range [0,1], and all coordinates are expressed
with respect to the absolute coordinate system.
For more information about surface evaluators, please refer to Chapter 9 of the SNAP Getting Started guide.
Primitive Features
GRIP commands like SOLBLK, SOLCYL and so on to create primitive features. SNAP has analogous functions like
Snap.Create.Block, Snap.Create.Cylinder, and so on. The SNAP functions typically have several overloads providing
different construction options.
SOLBLK/ Block( ) The GRIP and SNAP functions use the WCS and ACS respectively to align the
block. Or, in some SNAP functions, an orientation can be input.
SOLTOR/ Torus( ) The GRIP SOLTOR command creates an orphan solid body, rather than a feature.
The Snap.Create.Torus function can create either a sheet body or a solid body,
depending on its inputs. In either case, the output is an NX.Revolve feature.
SOLEXT/ Extrude( ) Both the SNAP and GRIP functions create Extrude features
ExtrudeSheet( )
SOLREV/ Revolve( ) Both the SNAP and GRIP functions create Revolve features
RevolveSheet( )
Create Prism
The GRIP SOLPRI command creates an n-sided prism. There is no direct analog either in SNAP or NX Open, except
for a very old C function called UF6505.
SOLPRI/ UF6505( ) The GRIP SOLPRI command creates an orphan solid body, rather than a
feature.
Joining Operations
The GRIP commands UNITE, SUBTRA and INTERS allow you to perform boolean operations on solid and sheet bodies
(with certain restrictions). The analogous SNAP functions are Snap.Create.Unite, Snap.Create.Subtract, and
Snap.Create.Intersect. THE GRIP SEW command allows you to sew sheet bodies together.
BLEND/ EdgeBlend( ) The GRIP command creates either an EdgeBlend or Chamfer feature.
FaceBlend( )
Chamfer( )
BLENFX/ --- In SNAP and NX Open, blends are always fixed when they are created, so no
separate fix operation is required.
SPLIT/ SplitBody( ) Split a body using a sheet body, faces, or a datum plane
TrimBody( )
Drawings
In NX Open, functions related to drawings can be found in the NXOpen.Drawings namespace, and in the
NXOpen.UF.UFDraw class. Note that the documentation for the NXOpen.UF.UFDraw class contains many sample
programs. While these are written in the C language, conversion to other languages is typically straightforward.
A drawing is represented by a collection of NXOpen.Drawings.DrawSheet objects in NX Open. The set of all
DrawingSheet objects in the work part (or any part file) is a DrawingSheetCollection object, which you can get by
using the workPart.DrawingSheets property.
Each sheet has a SheetDraftingViewCollection object, which is important because you use it to work with the views
on the sheet (to create and delete views, for example). You can get this object by using the SheetDraftingViews
property of the sheet.
sheets = workPart.DrawingSheets
DRAWC/ sheets.InsertSheet( ) Create a drawing
views = mySheet.SheetDraftingViews
DRAWE/ADD views.CreateBaseView( ) Add a view to a drawing
views.CreateProjectedView( )
views = mySheet.SheetDraftingViews
DRAWE/REMOVE Remove view from a drawing
views.DeleteView( )
sheets = workPart.DrawingSheets
dwg = &CURDRW Get the current drawing (sheet)
dwg = sheets.CurrentDrawingSheet
Dimensions
To create dimensions in a part, you use functions in its DimensionCollection object, which you can obtain by using
the Dimensions property of the part. Simple dimensions can be created directly; more complex ones are created
indirectly using the “builder” pattern that we have seen elsewhere in NX Open. Here are the functions for creating
dimensions (either directly or via builders):
CreateHorizontalDimension( )
LDIM/{HORIZ|VERT} CreateVerticalDimension( ) Horizontal or vertical dimension
CreateLinearDimensionBuilder( )
CreateAngularDimensionBuilder( )
CreateMajorAngularDimension( )
ADIM/ CreateMajorAngularDimensionBuilder( ) Angular dimension
CreateMinorAngularDimension( )
CreateMinorAngularDimensionBuilder( )
CreateArcLengthDimension( )
ARCDIM/ Arclength dimension
CreateCurveLengthDimensionBuilder( )
CreateHorizontalOrdinateDimension( )
ODIM/ CreateVerticalOrdinateDimension( ) Ordinate dimension
CreateOrdinateDimensionBuilder( )
assoc.FirstObject = myArc
assoc.SecondObject = Nothing
assoc.ObjectView = workPart.Views.WorkView
assoc.PickPoint = New Point3d(350, 650, 0)
Next, here’s how you do the same thing by using a builder, instead:
builder.Origin.Anchor = Annotations.OriginBuilder.AlignmentPosition.MidCenter
builder.Origin.Origin.SetValue(Nothing, Nothing, New Point3d(370, 670, 0))
builder.Origin.SetInferRelativeToGeometry(True)
Notes
To create a Note, you can use the SNAP function Snap.Create.Note. Alternatively, there are NX Open functions in the
AnnotationManager class:
The SNAP function creates a Snap.NX.Note object, which encloses an NXOpen.Annotations.PmiNote object.
To get or set the Work Layer, you use the Snap.Globals.WorkLayer property, which is equivalent to the GRIP &WLAYER
GPA symbol:
Each layer has one of four states described by the Snap.Globals.LayerState enumeration. These four states are
WorkLayer, Selectable, Visible, and Hidden. The state of layer number n is held in the variable
Snap.Globals.LayerStates(n).
To create a category in SNAP, you use the Snap.Create.Category function. This returns an object of type
Snap.NX.Category that has certain useful methods and properties as outlined below.
myCat.Delete( )
CATD/ Delete a category or a collection of categories
Category.Delete( )
myCat.Layers
CATV/LAYERS Get the layers in a category
myCat.LayerMask
19. Attributes
This section covers the GRIP statements that assign and delete attributes. Attributes can be assigned either to NX
part files, or to individual objects within part files. In both GRIP and SNAP, attributes are handled in more-or-less
the same way whether they are attached to objects or part files.
Assigning Attributes
In GRIP, attributes are assigned to either parts or objects using the ASATT command.
Code Type
1 Integer
2 Floating point
3 Date and time
4 Null
5 Character string
7 Reference
In SNAP, object attributes are assigned and read using functions in the NX.NXObject class, and there are different
functions for different attribute types. For example, if you have a body called bracket, you assign a “Cost” attribute
with a value of $17.95 to it using bracket.SetRealAttribute("Cost", 17.95). The Snap.NX.Part class has analogous
functions (with exactly the same names) for assigning attributes to parts.
Deleting Attributes
The functions for deleting attributes are:
In the Snap.NX.Part class, you will find analogous functions (with the same names) for reading part attributes. So,
for example, to read an Integer attribute from myPart, you call myPart.GetIntegerAttribute( ), and so on.
In SNAP, all date/time attributes are represented using .NET System.DateTime structures.
Object Types
In GRIP, each NX object has a “type”, and (in some cases) a “subtype”. Types and subtypes are indicated by integer
values, which can be obtained by using EDA’s called &TYPE and &SUBTYP. In SNAP, an object’s type is given by its
ObjectType property, whose value comes from the Snap.NX.ObjectTypes.Type enumeration. Similarly, an object’s
subtype is given by its ObjectSubType property, whose value comes from the Snap.NX.ObjectTypes.SubType
enumeration. The correspondences for a few cases are shown in the tables below. First for object types:
Point 2 Snap.NX.ObjectTypes.Type.Point
Line 3 Snap.NX.ObjectTypes.Type.Line
Arc/circle 5 Snap.NX.ObjectTypes.Type.Arc or
Snap.NX.ObjectTypes.Type.Circle
Conic 6 Snap.NX.ObjectTypes.Type.Conic
Spline 9 Snap.NX.ObjectTypes.Type.Spline
Dimension 26 Snap.NX.ObjectTypes.Type.Dimension
Conic-Ellipse 1 Snap.NX.ObjectTypes.SubType.ConicEllipse
Conic-Hyperbola 2 Snap.NX.ObjectTypes.SubType.ConicHyperbola
Conic-Parabola 3 Snap.NX.ObjectTypes.SubType.ConicParabola
Dimension-Horizontal 1 Snap.NX.ObjectTypes.SubType.DimensionHorizontal
Dimension-Vertical 2 Snap.NX.ObjectTypes.SubType.DimensionVertical
So, SNAP code for testing object types and subtypes looks like this:
The value of Snap.NX.ObjectTypes.Type.Conic is actually 6, which matches the value used in GRIP. So, you could write
If curveType = 6, instead of If curveType = NX.ObjectTypes.Type.Conic. But it’s best to avoid using numerical constants
like “6”, because they look mysterious in your code, and they might change at some point in the future. Use the
enumerated values, instead. They are rather long, but Visual Studio intellisense will do most of the typing for you.
General Functions
Many of the general functions described below are related to the general properties listed above. The property
values can typically be set without using any special function, so the functions are useful only when you want to set
the properties of several objects all at once. For example, using the Hide function is more convenient than setting
the IsHidden property of several objects. These functions can generally be found in the Snap.NX.NXObject class
Transformations
To transform objects in GRIP, you first use the MATRIX statement to construct a matrix that describes the effect of
the transformation. Then you apply the transformation by passing your matrix into the TRANSF command. The
approach in SNAP is similar. You first construct a Transform object using the functions in the Snap.Geom.Transform
class, and then you apply this transform to an object by using either the Snap.NX.NXObject.Move or
Snap.NX.NXObject.Copy functions. You can also transform Position and Vector objects.
DISTF/ Snap.Compute.Distance( ) Calculate the (minimum) distance between objects, and the
RELDST/ Snap.Compute.ClosestPoints( ) points at which the minimum distance is achieved.
Deviation
Deviation checking functions measure the maximum distance between two objects (curves and faces). The primary
use of these functions is to check whether two objects are (roughly) coincident. The GRIP DEVCHK/ statement
outputs results to the listing device, whereas the Snap.Compute.Devation functions return their results to the calling
function.
Arclength
The GRIP ANLSIS/ARCLEN statement calculates the arclength of a given collection of curves. In SNAP, each curve or
edge has an Arclength property. Alternatively, to compute the arclength of a collection of curves, all at once, you can
use the Snap.Compute.Arclength function.
For sheet and solid bodies, the Snap.Compute.MassProperties function computes properties such as areas, volumes,
mass, moments of inertia, and so on. Again, this function returns a structure containing the various results. If you
only need mass, volume, or surface area, there are specific functions for calculating these quantities, which you may
find easier to use.
GRIP has special options like ANLSIS/PROSOL and ANLSIS/VOLREV that allow you to compute the properties of
“implied” objects without actually constructing them. This is not supported in SNAP — if you want to compute the
properties of an object, you must fully construct it, first.
22. CAM
Currently, there are no SNAP functions for CAM, so we provide a brief introduction to NX Open functions, instead.
To gain access to CAM capabilities, you first obtain an NXOpen.CAM.CAMSetup object. There will be a CAMSetup
object in every part file that you use for CAM work, and typical code to obtain it (for the work part) is as follows:
In both cycling examples, note how we used the standard VB functions GetType and TypeOf to get and test the type
of an operation or an NCGroup. To perform the same sort of testing in GRIP, you would use an &OPTYP EDA symbol
together with “magic numbers” representing the operation types. The magic numbers are not needed in NX Open,
so the code is much more readable:
The types and subtypes of tools are handled in a different fashion. As the code above shows, there is a
GetTypeAndSubtype function. But, again, this does not return magic numbers, it returns values from two
enumerations, CAM.Tool.Types and CAM.Tool.Subtypes, which again leads to more readable code. For example, here
is how you would test for a threading tool of subtype “Acme”:
As you can see, the code turns on collision checking for all hole-drilling operations. For each operation, it creates a
builder, sets its CollisionCheck property to True, and then commits the builder to effect the change. To use this
approach, you have to know where to find the functions that create builders for various types of CAM objects (like
the CreateHoleDrillingBuilder function we used above). They can be found in two places: the
NXOpen.CAM.OperationCollection class contains builders for operations, and the NXOpen.CAM.NCGroupCollection
class contains builders for various types of CAM “groups”, which include tools, CAM geometry, and machining
methods. Some examples of the available functions are shown in the two tables below:
As you can see, the code sets CoolantThrough = True for every milling tool.
CAM Views
Within a given setup, the NCGroup and Operation objects are arranged hierarchically. There are actually four
independent tree structures: the Geometry view, the MachineMethod view, the MachineTool view, and the
ProgramOrder view, which correspond with the four possible views shown in the Operation Navigator in
interactive NX:
Any given operation will appear in all four of these views. As the name implies, the four views just provide us with
four different ways of looking at the same set of operations. In NX Open, the four view types are described by the
four values of the NXOpen.CAM.CAMSetup.View enumeration. An NCGroup object has GetParent and GetMembers
functions, so we can navigate up and down each tree. An Operation object has a GetParent function that tells us its
parent in each of the four views. There is also a GetRoot function that gives us the root of each view tree.
So, the code to get the root of each view and the first-level members is as follows:
When we create a new “group” object (like a tool), it must be correctly placed in one of these four views, by
indicating which group should be its parent. When we create an operation object, it must be correctly placed in all
four views, so we need to specify four parents. Further details can be found in the next two sections, which discuss
creation of tools and operations.
The definition of camFalse is not important; it’s only purpose is to avoid writing a very long line of code later on.
The most important function shown is CreateTool which (not surprisingly) creates a tool object. The first parameter
indicates which group should be the parent of the new tool; by specifying the machineRoot group, we are indicating
that the new tool should be placed at the top level of the MachineTool view hierarchy.
The “mill_planar” and “BALL_MILL” strings indicate the tool type and subtype respectively. These are the same
strings that appear in the Insert Tool dialog in interactive NX. Some example values for this pair of strings are:
mill_planar CHAMFER_MILL
mill_planar BALL_MILL
mill_planar SPHERICAL_MILL
mill_planar T_CUTTER
mill_planar BARREL
hole_making COUNTER_SINK
hole_making COUNTER_BORE
drill COUNTERSINKING_TOOL
drill COUNTERBORING_TOOL
Our next task is to specify specific values for various tool parameters like diameter and length. Since we have not
yet provided these values, our tool is just a generic “default” one. Continuing from above, the necessary code is:
toolBuilder.TlDiameterBuilder.Value = 4.5
toolBuilder.TlHeightBuilder.Value = 15
toolBuilder.TlNumFlutesBuilder.Value = 4
toolBuilder.Description = "Example ball mill"
toolBuilder.HelicalDiameter.Value = 80.0
toolBuilder.Commit()
toolBuilder.Destroy()
The pattern should be familiar, by now: we create a builder, modify its values, and then commit and destroy. This is
essentially the same editing process that we used in an earlier example. The only difference here is that we had to
create a default tool before we started the editing process.
File Operations
The table below shows the GRIP functions for working with files in general, and their analogs in VB:
Directory Cycling
GRIP provides the DOPEN, DCLOSE, SOPEN, and SCLOSE functions for moving upwards and downwards within a tree
of directories. Then, within any given directory, you can use the DNEXT function to cycle through its contents (either
files or subdirectories), accessing header information.
There are no SNAP or NX Open functions for performing these kinds of operations, because rich facilities are
already provided by the .NET framework. The relevant .NET functions can be found in the System.IO.File,
System.IO.Directory, System.IO.FileInfo and System.IO.DirectoryInfo classes.
EnumerateDirectories( )
Returns an enumerable collection of directory names in a specified path.
These functions return enumerable collections, which you can then cycle through using For Each. One of the
overloads of the EnumerateFiles function has a SearchOption parameter that lets you indicate whether you want all
the files in the given directory and its sub-directories, or only the ones at the top level.
The .NET functions all use System.DateTime objects to represent dates and times.
On the other hand, there is other information that is specific to NX, which you can access using NX Open functions:
Reading
You can read a text file either one line at a time or all at once. Often, the simplest approach is to read all the lines of
text in the file into an array of strings, and then cycle through this array:
The streamreader keeps track of the “pointer” or “cursor” in the file, so, each time you call ReadLine, you get the next
available line of text. GRIP uses line numbers for this sort of cursor positioning, but this approach does not make
sense in the .NET world, since there is no concept of line numbering.
Writing
Techniques for writing text are similar. You can write an entire array of strings, all at once, like this:
Or, you can write lines one at a time using a StreamWriter object:
The code samples above are just illustrative fragments. In production code, you need to handle any exceptions that
are raised, and you need to properly dispose of the StreamReader and StreamWriter objects you create.
Environment Variables
The GRIP ENVVAR statement allows you to get and set the values of environment variables. In VB code, you do this
by using the functions in the System.Environment class. There are specific properties that give you access to common
environment variables, for example:
The most versatile functions are GetEnvironmentVariable and SetEnvironmentVariable, which allow you get and set
values of any environment variable, and also to create and delete environment variables.