NXOpen notes
.net documentation in chm formatEdit
https://docs.plm.automation.siemens.com/tdoc/nx/11/nx_api#uid:xid1162445:index_xid969099:xid961278
Journal notesEdit
Journal recordings select objects using literals so the object's specific name is recorded. This is problematic while recording journals to gain shortcuts to automating functions.
User object selectionEdit
Dim cue = "Please select the objects to be blanked" Dim dialog As Selection.Dialog = Selection.SelectObjects(cue) Dim result As Selection.Result = dialog.Show If result.Response <> NXOpen.Selection.Response.Cancel Then theSession.DisplayManager.BlankObjects(result.Objects) End If
Change Journal languageEdit
You can indicate which language should be used in the recorded code by choosing:
File tab → Preferences → User Interface → Tools → Journal
The available choices are C#, C++, Java, Python, and Visual Basic.
SNAPEdit
Another NX API called SNAP whose functions are usually much easier to find and understand. SNAP functions can be used for simple common operations, and NX Open functions for more complex ones. To do this, you may need to convert SNAP objects into NX Open objects, and vice-versa. We have tried to make these conversions as convenient as possible, so that SNAP and NX Open code can live together in peace and harmony.
A SNAP object is just a wrapper around a corresponding NX Open object — for example, a Snap.NX.Spline object is just a wrapper that encloses an NXOpen.Spline, and a Snap.NX.Sphere is a wrapper around an NXOpen.Features.Sphere object, and so on. So, if you have an NXOpen object, you can “wrap” it to create a Snap.NX object. In the other direction, if you have a Snap.NX object, you can “unwrap” it to get the NXOpen object that it encloses. There are hidden “implicit” conversions that do this wrapping and unwrapping for you, so often things just work without any extra effort. For example:
Dim snapPoint As Snap.NX.Point = Point(3,5,9) Dim session As NXOpen.Session = NXOpen.Session.GetSession session.Information.DisplayPointDetails(snapPoint) Dim pt As NXOpen.Point3d = snapPoint.Position
THE ABOVE CODE DOES NOT WORK IN MY ENVIRONMENT. Instead, this compiles:
Dim snapPoint As NX.Point snapPoint.X = 3 snapPoint.Y = 5 snapPoint.Z = 9 Dim session As NXOpen.Session = NXOpen.Session.GetSession session.Information.DisplayPointDetails(snapPoint) Dim pt As NXOpen.Point3d = snapPoint.Position
Convert from object to snap object:Edit
Going in the other direction (from NXOpen to SNAP) is not quite so streamlined. The approach using properties is not available, so you have to call the Wrap function to create a new SNAP object from the NXOpen one, like this:
Dim coords = New NXOpen.Point3d(3, 6, 8) Dim workPart As NXOpen.Part = Snap.Globals.WorkPart.NXOpenPart Dim nxopenPoint As NXOpen.Point = workPart.Points.CreatePoint(coords) Dim snapPoint As NX.Point = NX.Point.Wrap(nxopenPoint.Tag) ' Create a Snap.NX.Point Dim location As Position = snapPoint.Position ' Use its Position property
In the fourth line of code, we first get the tag of the NXOpen.Point object. Then we call the Wrap function, which gives us a new Snap.NX.Point object that “wraps” it. Then, in the last line, we can use the Position property of this new Snap.NX.Point object. As we saw above, the Wrap function receives an NXOpen.Tag as input. So, if you are working with older NXOpen functions that use tags, interoperability with SNAP is even easier. For example:
Dim ufSession = NXOpen.UF.UFSession.GetUFSession Dim pointTag As NXOpen.Tag Dim coords As Double() = {2, 6, 9} ufSession.Curve.CreatePoint(coords, ByRef pointTag) Dim snapPoint As NX.Point = NX.Point.Wrap(pointTag)
THE ABOVE CODE DOES NOT WORK IN MY ENVIRONMENT. Instead, this compiles:
Dim ufSession = NXOpen.UF.UFSession.GetUFSession Dim pointTag As NXOpen.Tag Dim coords As Double() = {2, 6, 9} ufSession.Curve.CreatePoint(coords, pointTag) Dim snapPoint As NX.Point = NX.Point.Wrap(pointTag)
Standard code preamble for sessions and partsEdit
Dim mySession As NXOpen.Session = NXOpen.Session.GetSession Dim parts As NXOpen.PartCollection = mySession.Parts Dim workPart As NXOpen.Part = parts.Work Dim theSession As NXOpen.Session = NXOpen.Session.GetSession Dim theWorkPart As NXOpen.Part = theSession.Parts.Work Dim theDisplayPart As NXOpen.Part = parts.Display Dim theUfSession As NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession Dim theDisplay As NXOpen.DisplayManager = theSession.DisplayManager Dim theUI As NXOpen.UI = NXOpen.UI.GetUI
PointsEdit
A Point3d object represents a location in 3D space.
Point3d objects are not persistent in NX. To create an equivalent persistent NX objec use type NXOpen.Point
Create a NX PointEdit
Dim workPart As Part = session.Parts.Work ' Get the Work Part Dim points As PointCollection = workPart.Points ' Get the PointCollection of the Work Part Dim coords As new Point3d(3, 5, 0) ' Define coordinates of point Dim p1 As Point = points.CreatePoint(coords) ' Create the point (add to collection) p1.SetVisibility(SmartObject.VisibilityOption.Visible)
The last line of code is necessary because an NXOpen.Point is a “SmartObject”, which is invisible by default. The code above is written out in a rather verbose way, to allow for complete explanation. In practice, you would typically write something like this:
Dim workPart As Part = session.Parts.Work ' Get the Work Part Dim coords As new Point3d(3, 5, 0) ' Define coordinates of point Dim p1 As Point = workPart.Points.CreatePoint(coords) 'Create the point p1.SetVisibility(SmartObject.VisibilityOption.Visible) 'Make it visible
One liner:
Dim p1 = NXOpen.Session.GetSession.Parts.Work.Points.CreatePoint( New Point3d(3,5,0) )
The properties of Point objects are as follows:
Data Type | Property | Access | Description |
---|---|---|---|
Double | X | get, set | The x-coordinate of the point. |
Double | Y | get, set | The y-coordinate of the point. |
Double | Z | get, set | The z-coordinate of the point. |
Convert point to point3dEdit
myDirection.Origin = New Point3d(pt.X, pt.Y, pt.Z) 'where pt is an NX point
Create a point3dEdit
UF tag | .net object |
---|---|
Dim coords As Double() = { 1.5, 2.5, 7 } Dim pointTag As NXOpen.Tag theUfSession.Curve.CreatePoint(coords, pointTag) theUfSession.Obj.SetLayer(pointTag, 30) |
Dim coordsPt As New NXOpen.Point3d(1.5, 2.5, 7) Dim myPoint As NXOpen.Point = theWorkPart.Points.CreatePoint(coordsPt) myPoint.Layer = 30 |
Convert from tag to object exampleEdit
Dim myPoint As NXOpen.Point = theWorkPart.Points.CreatePoint(coordsPt) Dim pointTag As NXOpen.Tag = myPoint.Tag theUfSession.Obj.SetLayer(pointTag, 30)
Convert from object to tag exampleEdit
Dim pointTag As NXOpen.Tag theUfSession.Curve.CreatePoint(coords, pointTag) Dim obj As NXOpen.TaggedObject = NXOpen.Utilities.NXObjectManager.Get(pointTag) Dim myPoint As NXOpen.Point = CType(obj, NXOpen.Point) myPoint.Layer = 30
Calling the NXObjectManager.Get function gives an NXOpen.TaggedObject, and then this is cast to type NXOpen.Point. In practice, this can be shortened by using an implicit cast:
Dim myPoint As NXOpen.Point = NXOpen.Utilities.NXObjectManager.Get(pointTag)
Factory ObjectsEdit
In NX Open, an object is usually not created by calling a constructor function. Instead, you use a “create” functionthat is a member function of some “factory” object. Typically you can get a suitable factory object from an NXOpen.Part object (usually the work part), or from an NXOpen.Session object. So, suppose for example, that we want to create a point in a part
named myPart. The relevant factory object is a PointCollection object called myPart.Points. So, the CreatePoint function can be found in the PointCollection class, and you use it as follows to create a point:
Dim coords As new Point3d(3, 5, 0) ' Define coordinates of point Dim points As PointCollection = myPart.Points ' Get the PointCollection of the myPart Dim p1 As Point = points.CreatePoint(coords) ' Create the point
Sometimes the factory object provides functions for directly creating objects, as in the example above. Other times,
the factory object provides functions for creating “builder” objects, instead, as discussed in the next section. The
following table shows some common examples of factory objects, how you obtain instances of these factory objects,
and what sorts of creation functions they provide:
Type of Factory Object | Instance of Factory Object | Example Creation Functions |
PointCollection | BasePart.Points | CreatePoint
CreateQuadrantPoint |
CurveCollection | BasePart.Curves | CreateLine
CreateArc CreateEllipse |
Features.FeatureCollection | Part.Features | CreateSphereBuilder
CreateDatumPlaneBuilder CreateExtrudeBuilder CreateStudioSplineBuilder |
Annotations.AnnotationManager | Part.Annotations | CreateNote
CreateLabel CreateDraftingNoteBuilder |
CAE.NodeElementManager | CAE.BaseFEModel.NodeElementMgr | CreateNodeCreateBuilder
CreateElementCreateBuilder |
CAM.OperationCollection | CAM.CAMSetup.CAMOperationCollection | CreateHoleMakingBuilder
CreateFaceMillingBuilder |
CAM.NCGroupCollection. | CAM.CAMSetup.CAMGroupCollection | CreateMillToolBuilder
CreateDrillSpotfaceToolBuilder |
DexManager | Session.DexManager | CreateIgesImporter
CreateStep203Creator |
PlotManager | BasePart.PlotManager | CreateCgmBuilder
CreatePrintBuilder |
Here are some further examples showing factory objects and their simple creation functions:
Dim coords As New NXOpen.Point3d(3, 5, 9) Dim pointFactory As NXOpen.PointCollection = workPart.Points Dim myPoint = pointFactory.CreatePoint(coords) Dim p1 As New NXOpen.Point3d(1, 6, 5) Dim p2 As New NXOpen.Point3d(3, 2, 7) Dim curveFactory As NXOpen.CurveCollection = workPart.Curves Dim myLine = curveFactory.CreateLine(p1, p2) Dim text As String() = { "Height", "Diameter", "Cost" } Dim origin As New NXOpen.Point3d(3,8,0) Dim horiz As NXOpen.AxisOrientation = NXOpen.AxisOrientation.Horizontal Dim noteFactory As NXOpen.Annotations.AnnotationManager noteFactory = workPart.Annotations Dim myNote = noteFactory.CreateNote(text, origin, horiz, Nothing, Nothing)
In this code, we have explicitly defined the factory objects, to emphasize the role that they play. But, in typical code, they would not be mentioned explicitly, and you’d just write:
Dim myPoint = workPart.Points.CreatePoint(coords) Dim myLine = workPart.Curves.CreateLine(p1, p2) Dim myNote = workPart.Annotations.CreateNote(text, origin, horiz, Nothing, Nothing)
The Builder PatternEdit
We saw above how various factory objects provide functions like CreatePoint, CreateLine, and CreateNote that let us create simple objects directly. However, if we tried to handle more complex objects this way, we would need creation functions with huge numbers of input arguments. To avoid this complexity, we first create a “builder” object, and then we use this to create the object we want. As an example, here is the code to build a sphere feature:
Dim nullSphere As NXOpen.Features.Sphere = Nothing '[1] Dim mySphereBuilder As NXOpen.Features.SphereBuilder '[2] mySphereBuilder = workPart.Features.CreateSphereBuilder(nullSphere) '[3] mySphereBuilder.Type = <whatever you want> '[4] mySphereBuilder.Center = <whatever you want> '[5] mySphereBuilder.Diameter = <whatever you want> '[6] mySphereBuilder.BooleanOption.Type = <whatever you want> '[7] Dim myObject As NXOpen.NXObject = mySphereBuilder.Commit '[8] mySphereBuilder.Destroy '[9]
[3] Create a “builder” object
[4 - 7] Modify its properties as desired
[8] "Commit" the builder to create a new object
[8] returns a generic NXOpen object that requires casting appropriately:
' Two steps: commit and explicit cast Dim myObject As NXOpen.Features.Sphere = builder.Commit Dim mySphere1 As NXOpen.Features.Sphere = CType(myObject, NXOpen.Features.Sphere) ' One step: commit and cast implicitly Dim mySphere2 As NXOpen.Features.Sphere = builder.CommitFeatur
In some cases, both the Commit and CommitFeature methods return Nothing, and you have to use the GetCommittedObjects function to obtain the created object(s).
Object typesEdit
List of types:Edit
Session.Parts.Work.Bodies Session.Parts.Work.Curves.Createline(p1, p2) Point3d(x, y, z) Body NXObject.AttributeInformation
Create a lineEdit
Imports NXOpen Module NXOpenSample Sub Main () Dim theSession = Session.GetSession() Dim workPart = theSession.Parts.Work Dim p1 As New Point3d(50, -100, 0) Dim p2 As New Point3d(50, 100, 0) Dim line1 = workPart.Curves.CreateLine(p1, p2) Guide.InfoWriteLine("Line created with length " & line1.GetLength) End Sub End Module
Write to info paneEdit
Guide.InfoWriteLine("This text is written to the info pane")
LinesEdit
Draw a line from two point3d pointsEdit
Equivalent menu-driven procedure is: Insert → Curve → Basic Curves
Dim workPart As NXOpen.Part = Snap.Globals.WorkPart.NXOpenPart Dim p0 As New NXOpen.Point3d(1, 2, 3) Dim p1 As New NXOpen.Point3d(4, 7, 5) Dim line1 As NXOpen.Line = workPart.Curves.CreateLine(p0, p1) Dim pt0 As NXOpen.Point = workPart.Points.CreatePoint(p0) Dim pt1 As NXOpen.Point = workPart.Points.CreatePoint(p1) Dim line2 As NXOpen.Line = workPart.Curves.CreateLine(pt0, pt1) line2.SetVisibility(SmartObject.VisibilityOption.Visible)
Note that we had to set the visibility of line2 because lines created via this method are invisible by default.
There are other ways to create lines, too. There is NXOpen.UF.UFCurve.CreateLine, and the NXOpen.LineCollection class also has some functions for creating lines along the axes of various types of surfaces of revolution.
The geometric properties of lines are:
Data Type | Property | Access | Description |
---|---|---|---|
Point3d | StartPoint | get | Start point (point where t = 0). |
Point3d | StartPoint | get | End point (point where t = 1). |
The StartPoint and EndPoint properties cannot be set directly, but the NXOpen.Line class provides setStartPoint, SetEndPoint, and SetEndPoints functions that let you modify a line:
Dim newPoint = New Point3d(6,7,9) myLine.SetEndPoint(newPoint)
A Guide function exists:Edit
Guide.CreateLine(0, 0, 0, 10, 0, 0) '(x0,y0,z0,x1,y1,z1)
Associative linesEdit
Equivalent menu-driven procedure is: Insert → Curve → Line
To create associative lines, use the AssociativeLineBuilder class.
Dim workPart As NXOpen.Part = Snap.Globals.WorkPart.NXOpenPart ' Create an AssociativeLineBuilder Dim lineNothing As NXOpen.Features.AssociativeLine = Nothing Dim builder As NXOpen.Features.AssociativeLineBuilder builder = workPart.BaseFeatures.CreateAssociativeLineBuilder(lineNothing) builder.Associative = True ' Define the start point Dim p0 As New NXOpen.Point3d(1, 2, 3) Dim pt0 As NXOpen.Point = workPart.Points.CreatePoint(p0) builder.StartPointOptions = NXOpen.Features.AssociativeLineBuilder.StartOption.Point builder.StartPoint.Value = pt0 ' Define the end point Dim p1 As New NXOpen.Point3d(4, 7, 5) Dim pt1 As NXOpen.Point = workPart.Points.CreatePoint(p1) builder.EndPointOptions = NXOpen.Features.AssociativeLineBuilder.EndOption.Point builder.EndPoint.Value = pt1 ' Create an associative line feature Dim result As NXOpen.NXObject = builder.Commit builder.Destroy()
The result object created by this code is actually an Associative Line feature, rather than a line. This has advantages, sometimes — the feature appears in the Part Navigator and some forms of editing are easier. To obtain an old-fashioned line from an AssociativeLine feature, add the following two lines to the code above:
Dim workPart As NXOpen.Part = Snap.Globals.WorkPart.NXOpenPart ' Create an AssociativeLineBuilder Dim lineNothing As NXOpen.Features.AssociativeLine = Nothing Dim builder As NXOpen.Features.AssociativeLineBuilder builder = workPart.BaseFeatures.CreateAssociativeLineBuilder(lineNothing) builder.Associative = True ' Define the start point Dim p0 As New NXOpen.Point3d(1, 2, 3) Dim pt0 As NXOpen.Point = workPart.Points.CreatePoint(p0) builder.StartPointOptions = NXOpen.Features.AssociativeLineBuilder.StartOption.Point builder.StartPoint.Value = pt0 ' Define the end point Dim p1 As New NXOpen.Point3d(4, 7, 5) Dim pt1 As NXOpen.Point = workPart.Points.CreatePoint(p1) builder.EndPointOptions = NXOpen.Features.AssociativeLineBuilder.EndOption.Point builder.EndPoint.Value = pt1 ' Create an associative line feature Dim result As NXOpen.NXObject = builder.Commit builder.Destroy() Dim assocLine As NXOpen.Features.AssociativeLine = result Dim myLine As NXOpen.Line = assocLine.GetEntities(0)
Arcs and CirclesEdit
Dim workPart As NXOpen.Part = Snap.Globals.WorkPart.NXOpenPart Dim curves As NXOpen.CurveCollection = workPart.Curves Dim length As Double = 8 Dim width As Double = 4 Dim half As Double = width / 2 Dim holeDiam As Double = half Dim pi As Double = System.Math.PI Dim twopi As Double = 2 * pi Dim p1, p2, p3, q1, q2, q3 As NXOpen.Point3d p1 = New Point3d(0, -half, 0) q1 = New Point3d(0, -half, length) p2 = New Point3d(0, 0, 0) q2 = New Point3d(0, 0, length) p3 = New Point3d(0, half, 0) q3 = New Point3d(0, half, length) ' Left and right sides curves.CreateLine(p1, q1) curves.CreateLine(p3, q3) Dim axisX = New Vector3d(0, 1, 0) ' Horizontal Dim axisY = New Vector3d(0, 0, 1) ' Vertical ' Top and bottom arcs curves.CreateArc(q2, axisX, axisY, half, 0, pi) curves.CreateArc(p2, axisX, axisY, half, pi, twopi) ' Top and bottom holes curves.CreateArc(q2, axisX, axisY, holeDiam / 2, 0, twopi) curves.CreateArc(p2, axisX, axisY, holeDiam / 2, 0, twopi)
Code above draws the following object
Arcs UFEdit
A Guide function exists:Edit
Guide.CreateCircle(0, 0, 0, 10) '(xc, yc, zc, r)
Associated ArcEdit
(Insert → Curve → Arc.)
The code in the previous section creates ordinary arc objects that are not associative. An associative arcmay be used instead. Use the AssociativeArcBuilder class or record the creation of an arc using Insert → Curve → Arc. Typical output:
' create the session Dim theSession As NXOpen.Session = NXOpen.Session.GetSession() ' create the workpart Dim workPart As NXOpen.Part = theSession.Parts.Work ' Create an AssociativeArcBuilder Dim arcNothing As NXOpen.Features.AssociativeArc = Nothing Dim builder As NXOpen.Features.AssociativeArcBuilder builder = workPart.BaseFeatures.CreateAssociativeArcBuilder(arcNothing) builder.Associative = True ' Set the type of associative arc builder.Type = NXOpen.Features.AssociativeArcBuilder.Types.ArcFromCenter ' Define the arc center point Dim centerCoords As New Point3d(1.1, 2.2, 0) Dim centerPoint As NXOpen.Point = workPart.Points.CreatePoint(centerCoords) builder.CenterPoint.Value = centerPoint ' Define the arc radius builder.EndPointOptions = NXOpen.Features.AssociativeArcBuilder.EndOption.Radius builder.Radius.RightHandSide = "7.89" ' Define the angular limits (in degrees) builder.Limits.StartLimit.LimitOption = GeometricUtilities.CurveExtendData.LimitOptions.Value builder.Limits.EndLimit.LimitOption = GeometricUtilities.CurveExtendData.LimitOptions.Value builder.Limits.StartLimit.Distance.RightHandSide = "22.2" builder.Limits.EndLimit.Distance.RightHandSide = "55.5" ' Create an associative arc feature and get its arc Dim myArcFeature As NXOpen.Features.AssociativeArc = CType(builder.Commit, Features.AssociativeArc) builder.Destroy() Dim myArc As NXOpen.Arc = CType(myArcFeature.GetEntities()(0), Arc)
The last line is optional.
Conic Section Curves 2DEdit
Simple functions for creating conic section curves (ellipses, parabolas, hyperbolas) can be found in the NXOpen.CurveCollection class. For example, one of the functions for creating an ellipse is as follows:
'Get the matrix of the current WCS Dim wcsMatrix As NXOpen.NXMatrix = workPart.WCS.CoordinateSystem.Orientation Dim pi As Double = System.Math.PI Dim center As New NXOpen.Point3d(0,0,0) ' Center point (absolute coordinates) Dim rX As Double = 2 ' Major Radius Dim rY As Double = 1 ' Minor radius Dim a0 As Double = 0 ' Start angle Dim a1 As Double = pi ' End angle Dim rot As Double = pi/6 ' Rotation angle workPart.Curves.CreateEllipse(center, rX, rY, a0, a1, rot, wcsMatrix)
This creates half of a full ellipse, lying in a plane parallel to the work plane, with its center at the absolute origin. The ellipse is rotated in its plane by an angle of 30 degrees (π/6 radians).
The NXOpen.Features.GeneralConicBuilder class allows you to create conic section curves by different techniques, by specifying various combinations of point and tangency constraints.
The NXOpen.UF.UFCurve class also provides the CreateConic, and EditConicData functions.
Splines (NXOpen.Spline)Edit
The NX Open functions for handling splines use a fairly conventional NURBS representation that consists of:
▪ Poles — An array of n 3D vectors representing poles (control vertices)
▪ Weights — An array of n weight values (which must be strictly positive)
▪ Knots — An array of n + k knot values: t[0], ... , t[n + k − 1]
The order and degree of the spline can be calculated from the sizes of these arrays, as follows:
▪ Let n = number of poles = Poles.Length
▪ Let npk = n + k = number of knots = Knots.Length
Then the order, k, is given by k = npk − n. Finally, as usual, the degree, m, is given by m = k − 1.
Weight values are not very visible within interactive NX — you can see them in the Info function, but you can’t modify them. Generally, the equation of a spline curve is given by a rational function (the quotient of two polynomials). This is why spline curves are sometimes known as NURBS (Non-Uniform Rational B-Spline) curves. If the weights are all equal (and specifically if they are all equal to 1), then some cancellation occurs, and the equation becomes a polynomial.
The simplest function for creating a spline is NXOpen.UF.UFModl.CreateSpline, because its inputs closely match the defining data outlined above. The code is as follows:
Dim n As Integer = 4 ' Number of poles Dim k As Integer = 3 ' Order of curve (degree = k-1 = 2) ' 3D coordinates of poles Dim p As Double(,) = { {1,0,0}, {3,1,0}, {5,1,0}, {6,0,0} } ' Weights Dim w As Double() = {1, 1, 0.7, 1} ' Construct 4D poles Dim poles4D(4*n-1) As Double For i As Integer = 0 to n-1 poles4D(4*i) = w(i) * p(i,0) poles4D(4*i + 1) = w(i) * p(i,1) poles4D(4*i + 2) = w(i) * p(i,2) poles4D(4*i + 3) = w(i) Next ' Knots must be an array of length n + k Dim knots As Double() = {0,0,0, 0.6, 1,1,1} Dim splineTag As NXOpen.Tag Dim knotFixup As Integer = 0 Dim poleFixup As Integer = 0 Dim ufs As NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession ufs.Modl.CreateSpline(n, k, knots, poles4D, splineTag, knotFixup, poleFixup)
Studio SplinesEdit
Studio Spline feature, instead, because this feature will appear in the Part Navigator and some forms of editing are easier. You proceed in the standard way, by first creating a StudioSplineBuilderEx object, and then setting its properties. For example, you can specify points that the spline should pass through, tangent directions, curvatures, and so on. To make the coding more convenient, let’s first write a small “helper” function that provides an easy way to add a “point” constraint to a StudioSplineBuilderEx object:
Private Shared Sub AddPoint(builder As Features.StudioSplineBuilderEx, coords As NXOpen.Point3d) Dim workPart As NXOpen.Part = NXOpen.Session.GetSession.Parts.Work Dim point As NXOpen.Point = workPart.Points.CreatePoint(coords) Dim geomCon As NXOpen.Features.GeometricConstraintData geomCon = builder.ConstraintManager.CreateGeometricConstraintData geomCon.Point = point builder.ConstraintManager.Append(geomCon) End Sub ' Create the builder Dim builder As NXOpen.Features.StudioSplineBuilderEx builder = workPart.Features.CreateStudioSplineBuilderEx(Nothing) ' Set a few properties builder.Type = NXOpen.Features.StudioSplineBuilderEx.Types.ByPoles builder.IsSingleSegment = True builder.IsAssociative = True ' Add some point constraints Dim pt1 As New NXOpen.Point3d(0, 7, 1) : AddPoint(builder, pt1) Dim pt2 As New NXOpen.Point3d(2, 7, 1) : AddPoint(builder, pt2) Dim pt3 As New NXOpen.Point3d(5, 9, 0) : AddPoint(builder, pt3) ' Create the Studio Spline Feature Dim splineFeature As NXOpen.Features.StudioSpline = builder.Commit ' Get the spline curve (if necessary) Dim spline As NXOpen.Spline = builder.Curve builder.Destroy
SketchesEdit
A sketch is a collection of curves that are controlled by a system of geometric and dimensional constraints. The system of constraints is solved to give the sketch curves the desired size and shape.
creating a datum plane and a datum axis to control the orientation of our sketch
Dim origin As New NXOpen.Point3d(0,0,0) Dim axisX As New NXOpen.Point3d(1,0,0) Dim wcsMatrix As NXOpen.Matrix3x3 = workPart.WCS.CoordinateSystem.Orientation.Element Dim sketchPlane As NXOpen.DatumPlane = workPart.Datums.CreateFixedDatumPlane(origin, wcsMatrix) Dim horizAxis As NXOpen.DatumAxis = workPart.Datums.CreateFixedDatumAxis(origin, axisX)
create an empty sketch (that does not yet contain any curves), using the familiar builder technique:
Dim sketchBuilder As NXOpen.SketchInPlaceBuilder sketchBuilder = workPart.Sketches.CreateNewSketchInPlaceBuilder(Nothing) sketchBuilder.PlaneOrFace.Value = sketchPlane sketchBuilder.Axis.Value = horizAxis sketchBuilder.SketchOrigin = workPart.Points.CreatePoint(origin) sketchBuilder.PlaneOption = NXOpen.Sketch.PlaneOption.Inferred Dim bridgeSketch As NXOpen.Sketch = sketchBuilder.Commit sketchBuilder.Destroy bridgeSketch.Activate(NXOpen.Sketch.ViewReorient.False)
The last line of code activates the sketch, allowing us to add curves and constraints to it. Next, we create an arc through three points, and add it to our sketch:
Dim p0 As New NXOpen.Point3d(2,0,0) ' Start point Dim p1 As New NXOpen.Point3d(0,0,0) ' End point Dim pm As New NXOpen.Point3d(1,1,0) ' Interior point Dim gotFlipped As Boolean = False Dim bridge As NXOpen.Arc = workPart.Curves.CreateArc(p0, pm, p1, False, gotFlipped) theSession.ActiveSketch.AddGeometry(bridge, NXOpen.Sketch.InferConstraintsOption.InferNoConstraints)
The next step is to create some constraints that make the start and end points of the arc coincident with the two given points p0 and p1.
Dim arcPt0 As New NXOpen.Sketch.ConstraintGeometry arcPt0.Geometry = bridge arcPt0.PointType = NXOpen.Sketch.ConstraintPointType.StartVertex arcPt0.SplineDefiningPointIndex = 0 Dim pt0 As New NXOpen.Sketch.ConstraintGeometry pt0.Geometry = workPart.Points.CreatePoint(p0) pt0.PointType = NXOpen.Sketch.ConstraintPointType.None pt0.SplineDefiningPointIndex = 0 theSession.ActiveSketch.CreateCoincidentConstraint(arcPt0, pt0)
we do not use the point p0 and the arc end-point directly — we first construct ConstraintGeometry objects that are then used as input to the CreateCoincidentConstraint function. The code for constraining the arc’s end-point is analogous:
Dim arcPt1 As New NXOpen.Sketch.ConstraintGeometry arcPt1.Geometry = bridge arcPt1.PointType = NXOpen.Sketch.ConstraintPointType.EndVertex arcPt1.SplineDefiningPointIndex = 0 Dim pt1 As New NXOpen.Sketch.ConstraintGeometry pt1.Geometry = workPart.Points.CreatePoint(p1) pt1.PointType = NXOpen.Sketch.ConstraintPointType.None pt1.SplineDefiningPointIndex = 0 theSession.ActiveSketch.CreateCoincidentConstraint(arcPt1, pt1)
The “coincidence” constraint we have used here is the most common type, but the Sketch class provides functions for creating many other types. For example, parallel, perpendicular and concentric constraints are supported, as ininteractive NX. Next, we create a “perimeter” dimension to control the length of the arc:
Dim length As NXOpen.Expression = workPart.Expressions.CreateExpression("Number", "length = 2.5") Dim perimeter As NXOpen.Curve() = {bridge} theSession.ActiveSketch.CreatePerimeterDimension(perimeter, origin, length)
Typically, the perimeter of a sketch will consist of an array of curves, of course, but here we have only one. Again, the Sketch class provides functions for creating various other types of dimensional constraints (linear, angular, diameter, and so on). Finally, we “update” the sketch, and deactivate it.
theSession.ActiveSketch.LocalUpdate theSession.ActiveSketch.Deactivate(NXOpen.Sketch.ViewReorient.False, NXOpen.Sketch.UpdateLevel.Model)
When we call the LocalUpdate function, the sketch is solved, but the children of the sketch (if any) are not updated. After executing the code, the user can adjust the value of the “length” expression to modify the shape of the curve.
SolidsEdit
PrimitivesEdit
' create the session Dim theSession As NXOpen.Session = NXOpen.Session.GetSession() ' create the workpart Dim workPart As NXOpen.Part = theSession.Parts.Work Dim builder As NXOpen.Features.SphereBuilder builder = workPart.Features.CreateSphereBuilder(Nothing) ' Specify the sphere definition type (center and diameter) builder.Type = Features.SphereBuilder.Types.CenterPointAndDiameter ' Define the sphere center Dim center As New NXOpen.Point3d(3, 5, 6) Dim centerPoint As NXOpen.Point = workPart.Points.CreatePoint(center) builder.CenterPoint = centerPoint ' Define the sphere diameter Dim diamString As String = "1.5" builder.Diameter.RightHandSide = diamString ' Define the boolean option (create, unite, etc.) builder.BooleanOption.Type = NXOpen.GeometricUtilities.BooleanOperation.BooleanType.Create ' Commit to create the feature Dim sphereObject As NXOpen.Features.Sphere = CType(builder.CommitFeature, Features.Sphere) ' Destroy the builder to free memory builder.Destroy()
▪ Create a “builder” object
▪ Modify its properties as desired
▪ “Commit” the builder to create a new feature
Functions to create various types of “builder” objects are methods of a FeatureCollection object, and we can get one of these from the workPart.Features property.
Can create Block, Cylinder and Cone features using similar techniques. As you would expect, the relevant builder objects are BlockFeatureBuilder, CylinderBuilder, and ConeBuilder.
ConesEdit
Dim builder = workPart.Features.CreateConeBuilder(Nothing) ' Specify the cone definition type (diameters and height) builder.Type = NXOpen.Features.ConeBuilder.Types.DiametersAndHeight ' Define the diameters and height (these settings are relevant) builder.BaseDiameter.RightHandSide = "3" builder.TopDiameter.RightHandSide = "1.0" builder.Height.RightHandSide = "4" ' Try to define HalfAngle (no error; this is just ignored) builder.HalfAngle.RightHandSide = "1"
SpheresEdit
Guide.CreateSphere(x, y, z, 10) 'Create a sphere at (x,y,z) with diameter 10
Extract information from 3D objectEdit
Sub to get object attributesEdit
Sub PrintAttributes(obj As NXObject) Dim attributes = obj.GetUserAttributes() For Each attribute As NXObject.AttributeInformation In attributes Guide.InfoWriteLine(attribute.Title & " = " & attribute.StringValue) Next attribute End Sub
SectionsEdit
When you are selecting curves for use in Extrude, or Revolve, or many other NX functions, a menu appears in the top border bar showing you the available “Selection Intent” rules. This menu allows you to define a collection of curves that is dynamic in the sense that its members are determined on-the-fly based on the rule you specify. So, for example, if you select a face F and choose the “Face Edges” rule, your collection will contain all the edges of the face F. If the face F happens to change, as the result of model editing, then your collection will still consist of all the edges of F, whatever these might now be. The collection of curves is “smart” in the sense that it responds to changes in the model; in fact, as we will see, a collection defined in this way is sometimes referred to as a “Smart Collector”.
In NX Open, there is a corresponding SelectionIntentRule class, which has numerous derived classes, including
- CurveDumbRule
- CurveChainRule
- CurveFeatureChainRule
- CurveFeatureRule
- CurveFeatureTangentRule
- CurveGroupRule
- CurveTangentRule
The simplest type of these is the CurveDumbRule, which just collects a specific list of curves, as its name suggests. In an NX Open program, this is often appropriate, since the collection logic will reside in your code, rather than in NX data structures.
To create a selection intent rule of type CurveDumbRule from a given array of curves, the code is just:
Dim dumbrule As CurveDumbRule = workPart.ScRuleFactory.CreateRuleCurveDumb(curveArray)
The “Sc” in ScRuleFactory stands for “Smart Collector”. Then, once we have this rule, we can use it to add curves to a section. So, if we have a single curve named arc, the code to create a section is:
' Create a selection intent rule specifying a single arc Dim dumbRule As NXOpen.CurveDumbRule = workPart.ScRuleFactory.CreateRuleBaseCurveDumb({arc}) Dim rules As NXOpen.SelectionIntentRule() = {dumbRule} ' Create a section Dim mySection As NXOpen.Section = workPart.Sections.CreateSection(0.0095, 0.01, 0.5) Dim help As New NXOpen.Point3d(0,0,0) Dim nullObj As NXOpen.NXObject = Nothing ' Use the rule to add the arc to the section Dim noChain As Boolean = False mySection.AddToSection(rules, arc, nullObj, nullObj, help, NXOpen.Section.Mode.Create, noChain)
If we want a rectangular section consisting of four lines, then we add these one at a time, as follows:
' Create four lines Dim c1 = workPart.Curves.CreateLine(New Point3d(1,0,0), New Point3d(3,0,0)) Dim c2 = workPart.Curves.CreateLine(New Point3d(3,0,0), New Point3d(3,1,0)) Dim c3 = workPart.Curves.CreateLine(New Point3d(3,1,0), New Point3d(1,1,0)) Dim c4 = workPart.Curves.CreateLine(New Point3d(1,1,0), New Point3d(1,0,0)) Dim ctol = 0.0095 Dim dtol = 0.01 Dim atol = 0.5 ' Chaining tolerance ' Distance tolerance ' Angle tolerance ' Create a rectangular section Dim rect As NXOpen.Section = workPart.Sections.CreateSection(ctol, dtol, atol) Dim helpPoint As New NXOpen.Point3d(0,0,0) Dim nullObj As NXOpen.NXObject = Nothing Dim noChain As Boolean = False Dim createMode As NXOpen.Section.Mode = Section.Mode.Create ' Create rules to add the four lines to the section Dim r1 As NXOpen.CurveDumbRule = workPart.ScRuleFactory.CreateRuleBaseCurveDumb({c1}) Dim r2 As NXOpen.CurveDumbRule = workPart.ScRuleFactory.CreateRuleBaseCurveDumb({c2}) Dim r3 As NXOpen.CurveDumbRule = workPart.ScRuleFactory.CreateRuleBaseCurveDumb({c3}) Dim r4 As NXOpen.CurveDumbRule = workPart.ScRuleFactory.CreateRuleBaseCurveDumb({c4}) rect.AddToSection({r1}, c1, nullObj, nullObj, helpPoint, createMode, noChain) rect.AddToSection({r2}, c2, nullObj, nullObj, helpPoint, createMode, noChain) rect.AddToSection({r3}, c3, nullObj, nullObj, helpPoint, createMode, noChain) rect.AddToSection({r4}, c4, nullObj, nullObj, helpPoint, createMode, noChain)
Using other types of rules is quite similar. For example, if we want a section that gathers together all the edges of aface myFace, we write:
Dim faceRule As NXOpen.EdgeBoundaryRule = workPart.ScRuleFactory.CreateRuleEdgeBoundary({myFace}) mySection.AddToSection({faceRule}, myFace, nullObj, nullObj, help, NXOpen.Section.Mode.Create, False)
Extruded BodiesEdit
So, suppose we have created a section called mySection, as in the code above. To extrude this section in the z-direction we write:
' Create an ExtrudeBuilder Dim builder = workPart.Features.CreateExtrudeBuilder(Nothing) ' Define the section for the Extrude builder.Section = mySection ' Define the direction for the Extrude Dim origin As New NXOpen.Point3d(0,0,0) Dim axisZ As New NXOpen.Vector3d(0,0,1) Dim updateOption = SmartObject.UpdateOption.DontUpdate builder.Direction = workPart.Directions.CreateDirection(origin, axisZ, updateOption) ' Define the extents of the Extrude builder.Limits.StartExtend.Value.RightHandSide = "-0.25" builder.Limits.EndExtend.Value.RightHandSide = "0.5" Dim extrudeFeature As NXOpen.Features.Extrude = builder.CommitFeature builder.Destroy
If your section consists of an open string of curves that do not enclose a region, then the result will be a sheet body, of course. On the other hand, when you extrude a closed section, you can decide whether you want a sheet body or a solid body as the result. The draft angle(s) of the extruded body can be controlled by using the extrudeBuilder.Draft property, and thin-walled extrusions can be created using the extrudeBuilder.Offset property. So, to create a sheet body with a 15 degree draft angle, we write:
builder.FeatureOptions.BodyType = GeometricUtilities.FeatureOptions.BodyStyle.Sheet builder.Draft.DraftOption = GeometricUtilities.SimpleDraft.SimpleDraftType.SimpleFromProfile builder.Draft.FrontDraftAngle.RightHandSide = "15"
Revolved BodiesEdit
Suppose we have already created the rect section as shown above. To revolve this section around the y-axis, the code is:
' Create the Revolve builder Dim builder = workPart.Features.CreateRevolveBuilder(Nothing) ' Define the section for the Revolve (see above for details) builder.Section = rect ' Define the axis to revolve around (the y-axis of the Absolute Coordinate System) Dim axisPoint3d As New NXOpen.Point3d(0, 0, 0) Dim axisVector As New NXOpen.Vector3d(0, 1, 0) Dim updateOption = SmartObject.UpdateOption.WithinModeling ' Define a direction to pass the revolve point and axis to the builder Dim direction = workPart.Directions.CreateDirection(axisPoint3d, axisVector, updateOption) Dim axisPoint As NXOpen.Point = workPart.Points.CreatePoint(axisPoint3d) builder.Axis = workPart.Axes.CreateAxis(axisPoint, direction, updateOption) ' Define the extents of the Revolve (in degrees) builder.Limits.StartExtend.Value.RightHandSide = "0" builder.Limits.EndExtend.Value.RightHandSide = "90" ' Commit and then destroy the builder Dim revolveFeature As NXOpen.Features.Revolve = builder.CommitFeature builder.Destroy
NXObject Properties
Most objects in the NX Open object hierarchy inherit from NXOpen.NXObject, so its properties are very important because they trickle down to all the lower-level objects. The properties can be divided into several categories, as outlined below:
Type and Subtype Properties
Each NX Open object has a Type property and a Subtype property, which you will often use to make decisions about how to process the object. Some objects such as solid geometry objects have an additional SolidBodyType property. These properties are read-only.
Suppose the user has selected an object, for example. You might want to test whether this object is an ellipse before processing it. The code to do this would be as follows:
' Get the UFSession Dim ufs As NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession Dim thing As NX.NXObject = ... Dim myType As Integer Dim mySubType As Integer ufs.Obj.AskTypeAndSubtype(thing.Tag, myType, mySubType) If myType = NXOpen.UF.UFConstants.UF_conic_type And mySubType = NXOpen.UF.UFConstants.UF_conic_ellipse_subtype Then 'Do something End If
You can reduce the typing by putting Imports NXOpen.UF.UFConstants at the top of your file. In some cases, it might be more convenient to test the type of an object using the standard Visual Basic TypeOf function. For example, the code above could be written as:
Dim thing As NX.NXObject = ... If TypeOf thing Is NXOpen.Ellipse 'Do something End If
Display PropertiesEdit
Many of the objects that NX users deal with are of type NXOpen.DisplayableObject (a subtype derived from NXOpen.NXObject). These objects have the following properties:
Note that the Color attribute is a color index into the color palette for the part. The NXOpen.UF.UFDisp class
contains several functions for working with NX color indices. For example, NXOpen.UF.UFDisp.AskColor gets theRGB values associated with a given color index, and NXOpen.UF.UFDisp.AskClosestColor does the reverse.
List assembly children using recursionEdit
Public Shared Sub list() Dim session = NXOpen.Session.GetSession Dim workPart As NXOpen.Part = session.Parts.Work Try Dim root = workPart.ComponentAssembly.RootComponent DoSomething(root) Catch MsgBox("not assembly") End Try End Sub Public Shared Sub DoSomething(comp As NXOpen.Assemblies.Component) Guide.InfoWriteLine(comp.Name) For Each child In comp.GetChildren DoSomething(child) Next End Sub
Suppress / Unsuppress features (specifically sheetmetal)Edit
Imports System.Text.RegularExpressions Public Class myform Sub ToggleSheetMetalFeatures(oo As Boolean) Dim features As New List(Of NXOpen.Features.Feature) 'prep a list to receive the found features Dim theSession As NXOpen.Session = NXOpen.Session.GetSession() '} Dim workPart As NXOpen.Part = theSession.Parts.Work '} usual necessary things Dim displayPart As NXOpen.Part = theSession.Parts.Display '} Dim pattern As String = "^ConvertToSheetmetal" 'what we're looking for (could be an argument to function) Try theSession.Preferences.Sketch.CreateInferredConstraints = False '} theSession.Preferences.Sketch.ContinuousAutoDimensioning = False '} theSession.Preferences.Sketch.DimensionLabel = '} NXOpen.Preferences.SketchPreferences.DimensionLabelType.Expression '} theSession.Preferences.Sketch.TextSizeFixed = True '} theSession.Preferences.Sketch.FixedTextSize = 3.0 '} theSession.Preferences.Sketch.DisplayParenthesesOnReferenceDimensions = True '} theSession.Preferences.Sketch.DisplayReferenceGeometry = False '} set some options as per journal theSession.Preferences.Sketch.DisplayShadedRegions = True '} theSession.Preferences.Sketch.FindMovableObjects = True '} theSession.Preferences.Sketch.ConstraintSymbolSize = 3.0 '} theSession.Preferences.Sketch.DisplayObjectColor = False '} theSession.Preferences.Sketch.DisplayObjectName = True '} theSession.Preferences.Sketch.EditDimensionOnCreation = True '} theSession.Preferences.Sketch.CreateDimensionForTypedValues = True '} Catch Exit Sub End Try Try For Each feature In workPart.Features 'iterate through the feature list Dim featureName = feature.ToString 'get the name of each feature Dim m As Match = Regex.Match(featureName, pattern, RegexOptions.IgnoreCase) 'do the regex match If m.Success Then 'if the match is found then... TextBox1.AppendText("-------->" & featureName & vbCrLf) 'DEBUG features.Add(feature) '...add the feature to the list End If Next TextBox1.AppendText("Found: " & features.Count.ToString & vbCrLf) 'DEBUG Catch Exit Sub End Try Try For Each feature In features 'do something with the list items Dim features2(0) As NXOpen.Features.Feature '} Dim convertToSheetmetal2 As NXOpen.Features.ConvertToSheetmetal = '} CType(feature, NXOpen.Features.ConvertToSheetmetal) '} this slighly convoluted process is what the journal does so... features2(0) = convertToSheetmetal2 '} If oo = False Then workPart.Features.SuppressFeatures(features2) 'if oo (on/off) is false then unsuppress feature If oo = True Then workPart.Features.UnsuppressFeatures(features2) 'if oo (on/off) is true then suppress the feature TextBox1.AppendText("Changed state of: " & feature.ToString & vbCrLf) 'DEBUG Next Catch End Try End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click ToggleSheetMetalFeatures(False) End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ToggleSheetMetalFeatures(True) End Sub End Class
Signing DLL files[1]Edit
ReasonEdit
Once fully tested, an NXOpen API application should be signed before distribution to end users.
Even if the end users have access to the Author license which is required to load and run an NXOpen application, signing it has benefits:
- The application will load faster because NX will immediately recognize that it has been signed.
- The syslog (Help-> Log File) will not be cluttered with the output from the multiple checks that NX will do to determine whether it can load and run the program.
ProcedureEdit
- C/C++, C# or VB: Add the NXSigningResource to your Visual Studio project. In the Solution Explorer, select the Resource Files folder and <RMB>Add-> Existing Item. C# or VB .NET: and select %UGII_BASE_DIR%\UGOPEN\NXSigningResource.res Select the newly added NXSigningResource.res and in set Properties-> Build Action = Embedded Resource
- Make sure the build configuration is set to Release then Build-> Rebuild Solution
- Sign the executable from an NX Command Prompt window.
- Start-> All Programs-> NX#-> NX Tools-> Command Prompt
- C# or VB .NET
signDotNet <path to your .dll or .exe>
Note: cd to the path of the signing utility (like C:\Program Files\Siemens\NX2212\NXBIN).
Example:
signdotnet "D:\scm\Xtrac - NX Apps\XtracModelDrawingViewUtility\XtracUtil\bin\Release\DrawingViewUtility.dll"