Skip to content

Instantly share code, notes, and snippets.

@stephensmitchell
Created April 18, 2024 05:31
Show Gist options
  • Save stephensmitchell/8d7315ac0ab967f3cea2b02ebbf05442 to your computer and use it in GitHub Desktop.
Save stephensmitchell/8d7315ac0ab967f3cea2b02ebbf05442 to your computer and use it in GitHub Desktop.
Here are a few examples with AI cleanup tasks applied (untested) - Alibre Design code
' Global variables and types for interfacing with the AlibreX API
Public Session As IADSession
Public objADDesignSession As AlibreX.IADDesignSession
Public objADPartSession As AlibreX.IADPartSession
Public Dimension As Double
Public Hook As IAutomationHook
Public Root As IADRoot
' Conversion factor from inches to centimeters
Dim SysUnit = 2.54
' Dimension variables
Dim D4 = 2.6
' Boolean to control loops or conditional operations
Dim holdloop = True
' 3D and 2D Sketch variables for geometric drawing
Public Sketch3d As AlibreX.IAD3DSketch
Public Sketch2D As AlibreX.IADSketch
' Main subroutine where the program starts
Sub Main()
' Initialize automation hook and get the root object
Hook = GetObject(, "AlibreX.AutomationHook")
Root = Hook.Root
objADPartSession = Session
Dim currentPart As IADPartSession = Root.TopmostSession
' Output the file path of the current part
currentPart.FilePath.Dump()
Dim currentDateTime As DateTime = DateTime.Now
' Output formatted elapsed time
Util.ElapsedTime.ToString().Replace(":", "_").Replace(".", "_").Dump()
Dim timestamp As String = currentDateTime.ToString("MM-dd-yyyy-HH-mm-ss").Dump()
' Geometric construction functions
Helix1Geometry()
StepGeometry()
StepGeometry3()
' Adding a feature to the current part
currentPart.Features.AddExtrudedBoss(ReturnStepGeometry3(), 0.5 * SysUnit, AlibreX.ADPartFeatureEndCondition.AD_TO_DEPTH, Nothing, Nothing, 0, AlibreX.ADDirectionType.AD_ALONG_NORMAL, Nothing, Nothing, True, 0, False, "base")
' Save changes and release resources
currentPart.Save()
Hook = Nothing
Root = Nothing
End Sub
' Geometry parameters with units conversion
Public angle_a As Double = 30.000 * SysUnit
Public dia As Double = 10.000 * SysUnit
Public id As Double = 20.000 * SysUnit
Public od As Double = 40 * SysUnit
Public height As Double = 10 * SysUnit
Public pitch As Double = 60 * SysUnit
' Placeholder for base geometry creation
Public Sub BaseGeometry()
End Sub
' Function to create a 3D helix geometry
Public Sub Helix1Geometry()
Dim currentPart As IADPartSession = Root.TopmostSession
Dim currentDateTime As DateTime = DateTime.Now
Dim timestamp As String = currentDateTime.ToString("MM-dd-yyyy-HH-mm-ss").Dump()
Sketch3d = currentPart.Sketches3D.Add3DSketch(timestamp)
Sketch3d.BeginChange()
CreateHelixBspline(id, od, height, pitch)
CreateHelixBspline(id, 20*2.54, height, pitch)
Sketch3d.EndChange()
End Sub
' Function to delete all sketches in the current part session
Public Sub DeleteAllSketches()
Dim currentPart As IADPartSession = Root.TopmostSession
For Each item As IADSketch In currentPart.Sketches
item.Delete()
Next
currentPart.RegenerateAll()
End Sub
' Empty placeholder for future geometry methods
Public Sub Helix2Geometry()
End Sub
' Function to draw a step geometry using sketches
Public Sub StepGeometry3()
Dim currentPart As IADPartSession = Root.TopmostSession
Dim currentDateTime As DateTime = DateTime.Now
Dim timestamp As String = currentDateTime.ToString("MM-dd-yyyy-HH-mm-ss").Dump()
Sketch2D = currentPart.Sketches.AddSketch(Nothing, currentPart.DesignPlanes.Item("XY-Plane"), timestamp)
Sketch2D.BeginChange()
Dim Degrees30 As Double = 30 * (Math.PI / 180) ' Convert degrees to radians
Dim idr = 10 * SysUnit ' Inner diameter radius
Dim odr = 20 * SysUnit ' Outer diameter radius
sketch2D.Figures.AddCircularArc(0, 0, idr, 0, Degrees30)
sketch2D.Figures.AddCircularArc(0, 0, odr, 0, Degrees30)
Dim endPointIDR_X As Double = idr * Math.Cos(Degrees30)
Dim endPointIDR_Y As Double = idr * Math.Sin(Degrees30)
Dim endPointODR_X As Double = odr * Math.Cos(Degrees30)
Dim endPointODR_Y As Double = odr * Math.Sin(Degrees30)
sketch2D.Figures.AddLine(endPointIDR_X, endPointIDR_Y, endPointODR_X, endPointODR_Y)
sketch2D.Figures.AddLine(idr, 0, odr, 0)
Sketch2D.EndChange()
End Sub
' Function to create a B-spline curve for a helix shape
Function CreateHelixBspline(id As Double, od As Double, height As Double, pitch As Double) As IAD3DSketchBspline
Dim radius As Double = od / 2
Dim centerX As Double = 0
Dim centerY As Double = 0
Dim numTurns As Double = height / pitch
Dim order As Integer = 4 ' Cubic B-spline
Dim numCtlPoints As Integer = 500
Dim pCtlPoints(numCtlPoints * 3 - 1) As Double
For i As Integer = 0 To numCtlPoints - 1
Dim angle As Double = (i / numCtlPoints) * 2 * Math.PI * numTurns
Dim z As Double = (height * i) / numCtlPoints
pCtlPoints(i * 3) = centerX + radius * Math.Cos(angle)
pCtlPoints(i * 3 + 1) = centerY + radius * Math.Sin(angle)
pCtlPoints(i * 3 + 2) = z
Next
Dim pKnotVector(order + numCtlPoints) As Double
For i As Integer = 0 To pKnotVector.Length - 1
If i < order Then
pKnotVector(i) = 0
ElseIf i >= numCtlPoints Then
pKnotVector(i) = 1
Else
pKnotVector(i) = (i - order + 1) / (numCtlPoints - order + 1)
End If
Next
Dim pWeights(numCtlPoints - 1) As Double
For i As Integer = 0 To pWeights.Length - 1
pWeights(i) = 1
Next
Return Sketch3d.Figures.AddBspline(order, numCtlPoints, pCtlPoints, pKnotVector, pWeights)
End Function
' Declare global variables to hold various sessions and interfaces.
Public Session As IADSession
Public DesignSession As AlibreX.IADDesignSession
Public FeatureStep As AlibreX.IADPartSession
Public Hook As IAutomationHook
Public Root As IADRoot
' The Main subroutine acts as the entry point of the script.
Sub Main()
Try
' Attempt to retrieve the Alibre Automation Hook.
Hook = GetObject(, "AlibreX.AutomationHook")
' Access the root interface from the hook.
Root = Hook.Root
' Get the topmost session (the active session).
Session = Root.TopmostSession
' Assuming the session is a design session and part session both.
DesignSession = Session
FeatureStep = Session
' Make the first feature active to start the process.
FeatureStep.Features.Item(0).IsActive = True
' Wait for half a second to ensure the operation is processed.
Thread.Sleep(TimeSpan.FromSeconds(0.5))
' Iterate through each feature in the part session.
For Each item As IADPartFeature In FeatureStep.Features
' Activate the current feature.
item.IsActive = True
' Wait for half a second between activations to ensure smooth processing.
Thread.Sleep(TimeSpan.FromSeconds(0.5))
Next
' After activating all features, regenerate the part to apply changes.
FeatureStep.RegenerateAll()
' Save the part session.
FeatureStep.Save()
Catch ex As ArgumentException
' In case of an argument exception, display the error message.
MsgBox(ex.Message)
Finally
' Regardless of success or failure, clean up by setting interfaces to Nothing.
Hook = Nothing
Root = Nothing
End Try
End Sub
Public Class ExampleScript
' The Main subroutine that serves as the entry point of the application.
Public Sub Main()
' Getting command line arguments, though they're not used further in this snippet.
Dim ARGS = Environment.GetCommandLineArgs()
' Reading the XML file into an xDoc variable.
Dim xDoc = XDocument.Parse(File.ReadAllText("J:\Testbed-For-Alibre-Design\Alibre Design 27.0.0.27039\AlibreScript\AlibreScriptAPI.xml"))
' Converting XML to CSV and getting the List of CSV string lines.
Dim csvLines = ConvertToCsv(xDoc)
' Output operations for demonstration could go here.
' For example, writing to a file or iterating over csvLines to display them.
' Example of writing the output to a file directly:
File.WriteAllLines("C:\Users\steph\Desktop\ConvertedCSV.txt", csvLines)
' Previously, this line was incorrectly placed and used, it dumps data but doesn't serve the conversion process.
' File.ReadAllLines("C:\Users\steph\Desktop\alibre.script.api.text\alibre.script.api3.txt").Dump()
End Sub
' ConvertToCsv function processes an XDocument (XML) and returns a List of strings in CSV format.
Public Function ConvertToCsv(xDoc As XDocument) As List(Of String)
Dim newListOFStrings As New List(Of String)
' Adding CSV header to the list.
newListOFStrings.Add("Member Name,Summary")
' Iterating through each "member" element in the XML document.
For Each member In xDoc.Descendants("member")
' Extracting "name" attribute value, providing an empty string as fallback.
Dim name = If(member.Attribute("name")?.Value, "")
' Extracting and trimming the text of the "summary" element, with empty string as fallback.
Dim summary = If(member.Element("summary")?.Value.Trim(), "")
' Adding formatted CSV line to the list.
newListOFStrings.Add($"""{name}"",""{summary}""")
Next
Return newListOFStrings
End Function
End Class
' Declaration of global objects used throughout the session.
Dim Session As IADSession
Dim Hook As IAutomationHook
Dim Root As IADRoot
Dim AdPart As AlibreX.IADPartSession
' Constants for conversion and calculation purposes.
Dim SysUnit = 2.54
' Starting point of the script.
Sub Main()
' Initialize the design environment.
InitializeEnvironment()
' Perform CAD operations: in this case, adding a sketch and drawing a circular arc.
PerformCADOperations()
' Cleanup resources.
Cleanup()
End Sub
' Initializes the Alibre API environment and fetches the root session.
Private Sub InitializeEnvironment()
Hook = GetObject(, "AlibreX.AutomationHook")
Root = Hook.Root
Session = Root.TopmostSession
AdPart = Session
End Sub
' Carries out the specific CAD operations; adds a sketch and a circular arc to the part.
Private Sub PerformCADOperations()
' Predefined variables for specific operations, illustrating calculations and parameters.
Dim D1 As Double = 300
Dim D4 As Double = 10
Dim D7 As Double = 15
Dim C1 As Double = 16
' Calculated parameters for operations, likely related to specific feature dimensions.
Dim D10 As Double = C1 * (D1 - D7 - 2 * D4) / (Math.Pow(C1, 2) - C1)
' Fetch the XY-Plane to use as a reference for the sketch.
Dim objADDesignPlane As AlibreX.IADDesignPlane = Session.DesignPlanes.Item("XY-Plane")
' Add a new sketch to the part on the fetched design plane.
Dim objADSketch As AlibreX.IADSketch = AdPart.Sketches().AddSketch(Nothing, objADDesignPlane, "NewSketch")
' Begin batch modifications on the sketch.
objADSketch.BeginChange()
' Adds a circular arc to the sketch with specified parameters.
Dim objADSketchFigures As AlibreX.IADSketchFigures = objADSketch.Figures
Dim circularArcRadius As Double = 300
Dim circularArcStartAngle As Double = 0
Dim circularArcEndAngle As Double = -0.261799 ' Approximation of -15 degrees in radians.
objADSketchFigures.AddCircularArcByCenterStartAngle(0, 0, circularArcRadius, circularArcStartAngle, circularArcEndAngle)
' Commit the changes made to the sketch.
objADSketch.EndChange()
End Sub
' Releases COM objects and cleans up the environment.
Private Sub Cleanup()
' Cleans up the COM objects by setting them to Nothing.
Hook = Nothing
Root = Nothing
Session = Nothing
AdPart = Nothing
End Sub
' Variable declarations for global use.
Public Session As IADSession
Public objADDesignSession As AlibreX.IADDesignSession
Public objADPartSession As AlibreX.IADPartSession
Public Dimension As Double
Public Hook As IAutomationHook
Public Root As IADRoot
' Constants for unit conversion and other operations.
Dim SysUnit = 2.54
Dim D4 = 2.6
Dim holdloop = True
' Main subroutine as the entry point.
Sub Main()
' Establish connection to the Alibre Design application.
Hook = GetObject(, "AlibreX.AutomationHook")
Root = Hook.Root
' Assuming the first session is the desired one; adjust as necessary.
Session = Root.Sessions.Item(0)
objADDesignSession = Session
objADPartSession = Session
' Dumping file path of the session for debugging or information.
Session.FilePath.Dump()
' Dump total number of bodies in the session.
objADPartSession.Bodies.Count.Dump()
' Accessing the first body's vertices.
Dim b As AlibreX.IADBodies = objADPartSession.Bodies
Dim verts As AlibreX.IADVertices = b.Item(0).Vertices
verts.Count.Dump()
' Iterating through vertices and printing their coordinates.
For i As Integer = 0 To verts.Count - 1
printpoint(verts.Item(i).Point.X, verts.Item(i).Point.Y, verts.Item(i).Point.Z)
Next
' Final cleanup.
Hook = Nothing
Root = Nothing
End Sub
' A subroutine for additional connection strategies (unused in Main but provided for reference).
Sub Connection1()
Hook = GetObject(, "AlibreX.AutomationHook")
Root = Hook.Root
End Sub
' An alternative connection creation method which explicitly creates a new AutomationHook.
Sub Connection2()
Hook = New AlibreX.AutomationHook
Hook.Initialize("", "", "", True, 0)
Dim m_objADRoot As IADRoot = Hook.Root
End Sub
' Subroutine for printing point coordinates.
Sub printpoint(x As Double, y As Double, z As Double)
Console.WriteLine(x & " , " & y & " , " & z)
End Sub
Imports AlibreX
Imports System.IO
Public Class AlibreConstituentInfoExtractor
Public Session As IADSession
Public PartSession As IADPartSession
Public Hook As IAutomationHook
Public Root As IADRoot
<STAThread>
Sub Main()
Hook = GetObject(, "AlibreX.AutomationHook")
Root = Hook.Root
Session = Root.TopmostSession
PartSession = Session
GetConstInfo()
' It's good practice to clean up COM objects in the reverse order of their creation.
Hook = Nothing
Root = Nothing
End Sub
Sub GetConstInfo()
' Reading each line from a specified file path; each line is expected to be a file path for an assembly.
For Each item As String In File.ReadAllLines("D:\Desktop\03-22-2024\ad_asm_file_list.txt")
Console.WriteLine($"Processing: {item}")
GetConstituentFilePaths(item)
Next
End Sub
Public Function GetConstituentFilePaths(AssemblyPath As String) As String
Dim constituentGuids As IObjectCollector = Root.NewObjectCollector
Dim constituentNames As IObjectCollector = Root.NewObjectCollector
Dim constituentRelativeFilePaths As IObjectCollector = Root.NewObjectCollector
Dim constituentAbsoluteTPLocations As IObjectCollector = Root.NewObjectCollector
Dim constituentRelativeTPLocations As IObjectCollector = Root.NewObjectCollector
Dim guid As String = Nothing
' Assuming GetGuidAndConstituentInformation is the correct method based on the context.
' Be aware to pass `ByRef` for `guid` if the method expects to modify its input parameter.
Root.GetGuidAndConstituentInformation(AssemblyPath, guid, constituentGuids, constituentNames, constituentRelativeFilePaths)
' Example on how to iterate over IObjectCollector contents if needed
' You might need to adjust the iteration based on the actual type and content of the collector items.
For Each id In constituentGuids
Console.WriteLine($"GUID: {id}")
Next
For Each name In constituentNames
Console.WriteLine($"Name: {name}")
Next
For Each path In constituentRelativeFilePaths
Console.WriteLine($"Relative Path: {path}")
Next
' The original code did not actually return any meaningful value. Adjust based on what you need to return.
Return ""
End Function
End Class
#Region "Region Identifiers"
' Empty regions indicating unused placeholders for future code or previously removed code
#End Region
#Region "Properties"
' A property named "Test" with only trivial get and set implementations returning and setting nothing respectively
Public Property Test As Integer
Get
Return Nothing
End Get
Set(value As Integer)
End Set
End Property
#End Region
#Region "Axis Initialization"
' Initializes a design axis by creating two points and an axis between them
Sub InitAxis()
Dim i As AlibreX.IADDesignPoint = AdPart.DesignPoints.CreatePoint(1, 1, 1, "D")
Dim j As AlibreX.IADDesignPoint = AdPart.DesignPoints.CreatePoint(-1, -1, -1, "E")
Dim k As AlibreX.IADDesignAxis = AdPart.DesignAxes.CreateBy2Points(Nothing, i, Nothing, j, "F")
End Sub
#End Region
#Region "Extrude Initialization"
' Initializes an extrusion feature with specified parameters for a solid model
Sub InitExtrude()
Dim solid1 As AlibreX.IADPartFeatures = AdPart.Features
Dim solid2 As AlibreX.IADExtrusionFeature = solid1.AddExtrudedBoss(BaseSketch, 5, AlibreX.ADPartFeatureEndCondition.AD_TO_DEPTH, Nothing, Nothing, 0, AlibreX.ADDirectionType.AD_ALONG_NORMAL, Nothing, Nothing, True, 0.15, False, "base")
End Sub
#End Region
#Region "Main Initialization"
' Main variables and constants used throughout the code
Public Session As IADSession
Public Dimension As Double
Public Hook As IAutomationHook
Public Root As IADRoot
Public SysUnit = 2.54
Public holdloop = True
Public ADSketch As IADSketch = Nothing
' ... other variables are similarly defined here ...
' Setup method, initializes components and catches exceptions
Sub Setup()
Try
Hook = GetObject(, "AlibreX.AutomationHook")
Root = Hook.Root
Session = Root.TopmostSession
AdPart = Session
AdDesign = Session
' Calculations and additional setup code...
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
' Main entry point, calling various initialization subroutines and handling pauses between them
Sub Main()
Setup()
Thread.Sleep(TimeSpan.FromSeconds(5))
' Repeated calls to initialization methods with delays...
Finish()
End Sub
' Finalizes the design by regenerating it
Public Sub Finish()
AdPart.RegenerateDesign(True)
End Sub
' Utility functions for angle conversions
Public Function RadiansToDegrees(ByVal radians As Double) As Double
Return radians * (180 / Math.PI)
End Function
Public Function DegreesToRadians(ByVal degrees As Double) As Double
Return degrees * (Math.PI / 180)
End Function
#End Region
#Region "Additional Plane and Sketch Initializations"
' Additional methods for initializing other planes and sketches with specific geometric configurations
' Similar structure and functionality as previous initialization methods, with specific parameters and methods for creating geometric entities
' Example of another plane initialization method:
Sub InitPlane3()
Dim h As AlibreX.IADDesignPlane = a.CreateAtAngleToPlane(Nothing, b, Nothing, f, 0.785, "C")
End Sub
#End Region
#Region "Sweep Initialization"
' Initializes a sweep cutout feature using previously defined sketches and planes
Sub InitSweep()
Dim cut1 As AlibreX.IADPartFeatures = AdPart.Features
Dim cut2 As AlibreX.IObjectCollector = Root.NewObjectCollector
cut2.Add(path)
Dim cut3 As AlibreX.IADSweepFeature = cut1.AddSweptCutout(profile, cut2, False, AlibreX.ADPartFeatureEndCondition.AD_ENTIRE_PATH, Nothing, h2, 0, 0, False, "cut")
End Sub
#End Region
#Region "Arcs"
' Empty region previously intended for code related to arcs.
#End Region
#Region "ArcsTwo"
' Defines a property named Test with both getter and setter.
' Currently, the getter returns nothing and the setter does nothing.
Public Property Test As Integer
Get
Return Nothing ' Returns nothing.
End Get
Set(value As Integer)
' Does not store the provided value.
End Set
End Property
#End Region
#Region "Axis"
' Initializes a design axis between two points in a 3D CAD environment.
Sub InitAxis()
Dim i As AlibreX.IADDesignPoint ' Declare variable for the first point.
Dim j As AlibreX.IADDesignPoint ' Declare variable for the second point.
Dim k As AlibreX.IADDesignAxis ' Declare variable for the axis.
' Create first point at coordinates (1, 1, 1) named "D".
i = AdPart.DesignPoints.CreatePoint(1, 1, 1, "D")
' Create second point at coordinates (-1, -1, -1) named "E".
j = AdPart.DesignPoints.CreatePoint(-1, -1, -1, "E")
' Get the design axes collection.
Dim l As AlibreX.IADDesignAxes
l = AdPart.DesignAxes
' Create an axis between the two points and name it "F".
k = l.CreateBy2Points(Nothing, i, Nothing, j, "F")
End Sub
#End Region
#Region "Extrude"
' Initializes an extrusion feature in a CAD model.
Sub InitExtrude()
Dim solid1 As AlibreX.IADPartFeatures ' Declare variable to hold part features.
solid1 = AdPart.Features ' Get features from the part.
' Declare variable to hold the extrusion feature.
Dim solid2 As AlibreX.IADExtrusionFeature
' Create an extruded boss feature.
solid2 = solid1.AddExtrudedBoss(BaseSketch, 5, AlibreX.ADPartFeatureEndCondition.AD_TO_DEPTH, Nothing, Nothing, 0, AlibreX.ADDirectionType.AD_ALONG_NORMAL, Nothing, Nothing, True, 0.15, False, "base")
End Sub
#End Region
#Region "Init"
' Contains initializations of various session and configuration variables.
Public Session As IADSession
Public Dimension As Double
Public Hook As IAutomationHook
Public Root As IADRoot
Public SysUnit = 2.54 ' System unit in cm.
Public holdloop = True ' A flag to control some type of loop.
' Declarations related to sketches and design sessions.
Public ADSketch As IADSketch = Nothing
Public ADSketches As IADSketches = Nothing
Public ADSketchFigure As IADSketchFigure = Nothing
Public ADSketchFigures As IADSketchFigures = Nothing
Public AdPart As IADPartSession = Nothing
Public AdDesign As IADDesignSession = Nothing
Public BaseSketch As IADSketch
' Various dimension parameters used in design.
Public A1 = 15
Public C1 = 16
Public C2 = 1
Public D1 = 300
Public D11 = 0
Public D12 = 6
Public D2 = 120
Public D3 = 5
Public D4 = 10
Public D5 = D4
Public D6 = 300
Public D7 = 15
Public D8 = D4
Public D9 = D4 / 2
Public S1 = 0
Public S2 = 0
Public D10 = 0
Public OffsetHeight = 50
' Declaration of design plane and axis variables.
Public a As IADDesignPlanes
Public b As IADDesignPlane
Public f As IADDesignAxis
Public o As IADSketch
Public c As IADDesignPlane
Public profile As IADSketch
Public path As IADSketch
Public h As AlibreX.IADDesignPlane
Public h2 As AlibreX.IADDesignPlane
' Setup method to initialize the CAD environment and catch exceptions.
Sub Setup()
Try
' Connect to an existing instance of AlibreX AutomationHook.
Hook = GetObject(, "AlibreX.AutomationHook")
' Get the root object and top session from the hook.
Root = Hook.Root
Session = Root.TopmostSession
' Set part and design sessions.
AdPart = Session
AdDesign = Session
' Calculate a specific dimension parameter D10 based on other dimensions.
D10 = C1 * (D1 - D7 - 2 * D4) / (Math.Pow(C1, 2) - C1)
' Get the design planes collection and select a specific plane.
a = AdPart.DesignPlanes
b = a.Item("ZX-Plane")
Catch ex As Exception
' Output exception message to the console.
Console.WriteLine(ex.Message)
End Try
End Sub
' Main subroutine to run the full initialization sequence with delays.
Sub Main()
Setup() ' Initial setup.
Thread.Sleep(TimeSpan.FromSeconds(5)) ' Wait for 5 seconds.
InitPlaneOne ' Initialize the first plane.
Thread.Sleep(TimeSpan.FromSeconds(5)) ' Wait for 5 seconds.
InitSketch1 ' Initialize the first sketch.
Thread.Sleep(TimeSpan.FromSeconds(5)) ' Wait for 5 seconds.
InitSketch ' Initialize another sketch.
Thread.Sleep(TimeSpan.FromSeconds(5)) ' Wait for 5 seconds.
InitExtrude ' Initialize extrusion.
Thread.Sleep(TimeSpan.FromSeconds(5)) ' Wait for 5 seconds.
InitSweep ' Initialize sweeping.
Thread.Sleep(TimeSpan.FromSeconds(5)) ' Wait for 5 seconds.
Finish() ' Finish up.
End Sub
' Finish subroutine to regenerate the design.
Public Sub Finish()
AdPart.RegenerateDesign(True) ' Regenerate the design with rebuild.
End Sub
' Utility function to convert radians to degrees.
Public Function RadiansToDegrees(ByVal radians As Double) As Double
Dim degrees As Double
degrees = radians * (180 / Math.PI) ' Calculate degrees.
Return degrees ' Return the degrees.
End Function
' Utility function to convert degrees to radians.
Public Function DegreesToRadians(ByVal degrees As Double) As Double
Dim radians As Double
radians = degrees * (Math.PI / 180) ' Calculate radians.
Return radians ' Return the radians.
End Function
#End Region
#Region "Plane3"
' Initializes the third plane by creating it at an angle to another plane.
Sub InitPlane3()
h = a.CreateAtAngleToPlane(Nothing, b, Nothing, f, 0.785, "C") ' Create a plane at a 45-degree angle.
End Sub
#End Region
#Region "PlaneOne"
' Initializes the first plane by creating it offset to another plane.
Sub InitPlaneOne()
c = a.CreateAtOffsetToPlane(Nothing, b, OffsetHeight, "C") ' Create an offset plane.
End Sub
#End Region
#Region "PlaneTwo"
' Initializes the second plane by creating it at a negative angle to another plane.
Sub InitPlaneTwo()
f = AdPart.DesignAxes.Item("X-Axis") ' Get the X-axis.
Dim g As AlibreX.IADDesignPlane
g = a.CreateAtAngleToPlane(Nothing, b, Nothing, f, -0.785, "B") ' Create a plane at a -45-degree angle.
End Sub
#End Region
#Region "Sketch"
' Initializes a sketch on the XY-plane.
Sub InitSketch()
Dim base0 As AlibreX.IADSketches
base0 = AdPart.Sketches() ' Get the sketches collection.
BaseSketch = base0.AddSketch(Nothing, a.Item("XY-Plane"), "base") ' Add a new sketch to the XY-plane.
BaseSketch.BeginChange() ' Start modifying the sketch.
' Variables for creating a rectangle in the sketch.
Dim base1 As AlibreX.IADSketchFigures
base1 = BaseSketch.Figures ' Get the sketch figures collection.
Dim centerX As Double = 0 ' Center X coordinate.
Dim centerY As Double = 0 ' Center Y coordinate.
Dim w As Double = D1 ' Width of the rectangle.
Dim h As Double = D2 ' Height of the rectangle.
Dim xlow As Double = centerX - (w / 2) ' Left X coordinate.
Dim ylow As Double = centerY - (h / 2) ' Bottom Y coordinate.
Dim xhigh As Double = centerX + (w / 2) ' Right X coordinate.
Dim yhigh As Double = centerY + (h / 2) ' Top Y coordinate.
' Add a rectangle and a sketch point to the sketch.
base1.AddRectangle(xlow, ylow, xhigh, yhigh)
base1.AddSketchPoint(xhigh - D9, yhigh - D8)
' Create 2D points for additional design calculations.
Dim a2d = AdPart.DesignPoints.CreatePoint(xhigh - D9, yhigh - D8, 0, "1d")
Dim b2d = AdPart.DesignPoints.CreatePoint(xhigh - D9, yhigh - D8, D3, "2d")
' Create an axis for further operations.
Dim k As AlibreX.IADDesignAxis
Dim l As AlibreX.IADDesignAxes
l = AdPart.DesignAxes
k = l.CreateBy2Points(Nothing, a2d, Nothing, b2d, "F")
' Calculate and convert angles for plane creation.
Dim radians As Double = 1
Dim degrees As Double = RadiansToDegrees(radians)
h2 = a.CreateAtAngleToPlane(Nothing, a.Item("ZX-Plane"), Nothing, k, DegreesToRadians(15), "C")
' Add additional sketch points for completeness.
base1.AddSketchPoint(xhigh + D9, yhigh - D8)
Dim c2d = AdPart.DesignPoints.CreatePoint(xhigh + D9, yhigh - D8, D3, "4d")
Dim d2d = AdPart.DesignPoints.CreatePoint(xlow + D9, ylow - D8, D3, "5d")
Dim e2d = AdPart.DesignPoints.CreatePoint(xlow + D9, yhigh - D8, D3, "3d")
Dim f2d = AdPart.DesignPoints.CreatePoint(-(w / 2) + D4, OffsetHeight, D3, "9d")
BaseSketch.EndChange() ' Commit changes to the sketch.
End Sub
#End Region
#Region "Sketch1"
' Initializes a profile sketch for a sweep operation.
Sub InitSketch1()
Dim m As AlibreX.IADDesignPlane = a.Item("C") ' Get the plane named "C".
Dim n As AlibreX.IADSketches
n = AdPart.Sketches() ' Get the sketches collection.
profile = n.AddSketch(Nothing, c, "profile") ' Add a new sketch on plane "C".
' Variables for creating a profile with specific dimensions.
Dim edge_offset As Double = D1 - A1
Call profile.BeginChange() ' Start modifying the profile sketch.
Dim p As AlibreX.IADSketchFigures
p = profile.Figures ' Get the sketch figures collection.
Dim p_base As Double = A1 ' Base length of the profile.
Dim p_height As Double = D3 ' Height of the profile.
' Calculate translation factors for the profile.
Dim calc1 = (D1 / 2) - (D4 / 2) - 1
Dim calc2 = (calc1 - D7) + D12 + D3
Dim translation As Double = -calc2
' Define original vertices for the profile shape.
Dim originalVertices() As Double = {0 + translation, 0, p_base + translation, 0, p_base - p_height + translation, p_height, -p_height + translation, p_height}
Dim baseWidth As Double = originalVertices(2) - originalVertices(0)
Dim height As Double = originalVertices(7) - originalVertices(1)
' Calculate shear factors for the profile.
Dim shearFactorX As Double = baseWidth / height
Dim shearFactorY As Double = 0
' Apply shear transformation to the vertices.
Dim skewedVertices(originalVertices.Length - 1) As Double
For z As Integer = 0 To originalVertices.Length - 1 Step 2
Dim x As Double = originalVertices(z)
Dim y As Double = originalVertices(z + 1)
Dim skewedX As Double = x + y * shearFactorX
Dim skewedY As Double = y + x * shearFactorY
skewedVertices(z) = skewedX
skewedVertices(z + 1) = skewedY
Next
' Create lines based on the transformed vertices.
Dim numVertices As Integer = skewedVertices.Length / 2
Dim lines(numVertices - 1) As AlibreX.IADSketchLine
For v As Integer = 0 To numVertices - 1
Dim x1 As Double = skewedVertices(v * 2)
Dim y1 As Double = skewedVertices(v * 2 + 1)
Dim x2 As Double
Dim y2 As Double
If v = numVertices - 1 Then
x2 = skewedVertices(0)
y2 = skewedVertices(1)
Else
x2 = skewedVertices((v + 1) * 2)
y2 = skewedVertices((v + 1) * 2 + 1)
End If
lines(v) = p.AddLine(x1, y1, x2, y2)
Next
Call profile.EndChange() ' Commit changes to the profile sketch.
End Sub
#End Region
#Region "Sketch3"
' Initializes a path sketch for a sweeping operation.
Sub InitSketch3()
Dim path0 As AlibreX.IADSketches
path0 = AdPart.Sketches() ' Get the sketches collection.
path = path0.AddSketch(Nothing, a.Item("XY-Plane"), "path") ' Add a new sketch on the XY-plane.
path.BeginChange() ' Start modifying the path sketch.
Dim path1 As AlibreX.IADSketchFigures
path1 = path.Figures ' Get the sketch figures collection.
' Variables for creating a circular path.
Dim centerX As Double = 0 ' Center X coordinate.
Dim centerY As Double = 0 ' Center Y coordinate.
Dim w As Double = D1 ' Width of the circle.
Dim h As Double = D2 ' Height of the circle.
Dim xlow As Double = centerX - (w / 2) ' Left X coordinate.
Dim ylow As Double = centerY - (h / 2) ' Bottom Y coordinate.
Dim xhigh As Double = centerX + (w / 2) ' Right X coordinate.
Dim yhigh As Double = centerY + (h / 2) ' Top Y coordinate.
Dim l As AlibreX.IADDesignAxes
l = AdPart.DesignAxes ' Get the design axes collection.
Dim degrees As Double = DegreesToRadians(15) ' Convert 15 degrees to radians.
' Add a circular arc to the path.
path1.AddCircularArc(xhigh + D9, yhigh - D8, -D1 / 2 + D4, OffsetHeight, degrees)
path.EndChange() ' Commit changes to the path sketch.
End Sub
#End Region
#Region "Sweep"
' Initializes a sweeping operation in the CAD model.
Sub InitSweep()
Dim cut1 As AlibreX.IADPartFeatures
Dim cut2 As AlibreX.IObjectCollector
cut2 = Root.NewObjectCollector ' Create a new object collector.
cut2.Add(path) ' Add the path sketch to the collector.
cut1 = AdPart.Features ' Get the part features.
Dim cut3 As AlibreX.IADSweepFeature
' Create a swept cutout feature using the profile and path.
cut3 = cut1.AddSweptCutout(profile, cut2, False, AlibreX.ADPartFeatureEndCondition.AD_ENTIRE_PATH, Nothing, h2, 0, 0, False, "cut")
End Sub
#End Region
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment