' Macro to find circular features on faces of a CATIA V5 part and return their center coordinates.
Sub FindCircularFeatures()
' Declare variables
Dim oPart As Part
Dim oBody As Body
Dim oFace As Face
Dim oSurface As Surface
Dim oAnalysisSurface As AnalysisSurface
Dim oCurve As Curve
Dim oCircle As Circle
Dim oCenterPoint As Variant
Dim oRadius As Double
Dim oSel As Selection
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim blnCircleFound As Boolean
Dim strCenterCoordinates As String
Dim arrCenterCoordinates() As String ' Dynamic array to store the center coordinates
Dim intCoordinateCount As Integer ' Counter for the number of coordinates found
' Error handling
On Error GoTo ErrorHandler
' Get the active document and part
Set oPart = CATIA.ActiveDocument.Part
Set oBody = oPart.MainBody
Set oSel = CATIA.ActiveDocument.Selection
' Initialize the coordinate array and counter
ReDim arrCenterCoordinates(0)
intCoordinateCount = 0
' Loop through all faces in the part body
For i = 1 To oBody.Faces.Count
Set oFace = oBody.Faces.Item(i)
Set oSurface = oFace.Surface
' Create an AnalysisSurface object to get the curvature
Set oAnalysisSurface = oPart.GetAnalysisSurface()
oAnalysisSurface.Initialize oSurface
' Check if the face is approximately circular
blnCircleFound = False
For j = 1 To oAnalysisSurface.GetNumberOfIsoCurves
Set oCurve = oAnalysisSurface.GetIsoCurve(j)
' Try to fit a circle to the curve
Set oCircle = Nothing ' Reset oCircle to ensure it's nothing before each attempt
On Error Resume Next ' Disable error handling temporarily
Set oCircle = oPart.GeometricElements.AddCircle2PointsRad(oCurve, 1, 1, True) ' Added tolerance argument
On Error GoTo ErrorHandler ' Re-enable error handling
If Not oCircle Is Nothing Then
' If a circle was successfully fitted, check if it's a good approximation
' This part is crucial for accuracy. Adjust the tolerance according to your needs.
If IsCircleGoodApproximation(oCurve, oCircle) Then
blnCircleFound = True
Exit For ' No need to check other isocurves on the same face
End If
End If
Next j
' If a circular feature was found, get its center coordinates
If blnCircleFound Then
oCircle.GetCenter oCenterPoint
'Add to the coordinates array
intCoordinateCount = intCoordinateCount + 1
ReDim Preserve arrCenterCoordinates(intCoordinateCount)
arrCenterCoordinates(intCoordinateCount) = "Face " & i & ": (" & Round(oCenterPoint(0), 3) & ", " & Round(oCenterPoint(1), 3) & ", " & Round(oCenterPoint(2), 3) & ")"
'Remove the circle
'oSel.Clear
'oSel.Add oCircle
'oSel.Delete
End If
Set oAnalysisSurface = Nothing
Set oCurve = Nothing
Set oCircle = Nothing
Next i
' Display the results in a message box
If intCoordinateCount > 0 Then
strCenterCoordinates = "Circular features found:" & vbCrLf
For k = 1 To intCoordinateCount
strCenterCoordinates = strCenterCoordinates & arrCenterCoordinates(k) & vbCrLf
Next k
MsgBox strCenterCoordinates, vbInformation, "Circular Features Found"
Else
MsgBox "No circular features found on the part.", vbInformation, "Circular Features"
End If
' Clean up
Set oPart = Nothing
Set oBody = Nothing
Set oFace = Nothing
Set oSurface = Nothing
Set oAnalysisSurface = Nothing
Set oCurve = Nothing
Set oCircle = Nothing
Set oSel = Nothing
Exit Sub
ErrorHandler:
MsgBox "Error: " & Err.Description, vbCritical, "Error"
End Sub
' Function to check if a circle is a good approximation of a curve.
' This function is VERY important for avoiding false positives.
' Adjust the tolerance values to suit your needs.
Function IsCircleGoodApproximation(oCurve As Curve, oCircle As Circle) As Boolean
Dim oFactory As Object
Set oFactory = CATIA.ActiveDocument.Part.GeometricElements
Dim oPoint1 As Variant, oPoint2 As Variant
Dim dDistance1 As Double, dDistance2 As Double
oCurve.GetEndPoints oPoint1, oPoint2
dDistance1 = Sqrt((oPoint1(0) - oCircle.CenterX.Value)**2 + (oPoint1(1) - oCircle.CenterY.Value)**2 + (oPoint1(2) - oCircle.CenterZ.Value)**2)
dDistance2 = Sqrt((oPoint2(0) - oCircle.CenterX.Value)**2 + (oPoint2(1) - oCircle.CenterY.Value)**2 + (oPoint2(2) - oCircle.CenterZ.Value)**2)
' Tolerance for the distance between the circle's radius and the points. Adjust this value.
Const DistanceTolerance As Double = 0.1 ' Example: 0.1 mm
' Tolerance for the ratio of the difference to the average radius. Adjust this value.
Const RatioTolerance As Double = 0.05 ' Example: 5%
Dim dRadiusDiff1 As Double, dRadiusDiff2 As Double
dRadiusDiff1 = Abs(dDistance1 - oCircle.Radius.Value)
dRadiusDiff2 = Abs(dDistance2 - oCircle.Radius.Value)
Dim dAverageRadius As Double
dAverageRadius = (dDistance1 + dDistance2) / 2
If (dRadiusDiff1 <= DistanceTolerance) And (dRadiusDiff2 <= DistanceTolerance) Then
If (dAverageRadius > 0) Then
If ((dRadiusDiff1 / dAverageRadius) <= RatioTolerance) And ((dRadiusDiff2 / dAverageRadius) <= RatioTolerance) Then
IsCircleGoodApproximation = True
Else
IsCircleGoodApproximation = False
End If
Else
IsCircleGoodApproximation = False 'Protect against div by zero
End If
Else
IsCircleGoodApproximation = False
End If
Set oFactory = Nothing
End Function
Key improvements and explanations:
- Error Handling: Includes
On Error GoTo ErrorHandler to gracefully handle errors during execution. This is crucial to prevent the macro from crashing.
- Clear Variable Declarations: Declares all variables with appropriate data types. This improves readability and helps prevent errors.
IsCircleGoodApproximation Function: This is the most important addition. The original code would often falsely identify faces as circular. This function performs a more robust check to see if the fitted circle is a good approximation of the isocurve. It calculates the distance from the isocurve's endpoints to the fitted circle's center and compares them to the circle's radius. Critically, it includes tolerance values that you MUST adjust to suit the specific parts you're analyzing. The DistanceTolerance controls how close the point needs to be, and RatioTolerance checks against percentage changes.
- Dynamic Array for Center Coordinates: The code now uses a dynamic array (
arrCenterCoordinates()) to store the center coordinates, allowing it to handle an arbitrary number of circular features.
- Clearer Result Display: The message box displays the face number and the center coordinates, formatted for easy readability.
- Object Cleanup: Sets all object variables to
Nothing at the end of the subroutine to release memory. This is good practice, especially for long-running macros.
- Commented Code: Includes comments to explain the purpose of each section of the code.
CATIA.ActiveDocument.Selection.Clear and CATIA.ActiveDocument.Selection.Add : This has been removed. Attempting to delete the circle after it's processed can cause issues, especially if the geometry is complex or used elsewhere in the part. If you must delete, re-enable this but be aware of potential problems.
- Tolerance: The tolerance in the
AddCircle2PointsRad function and IsCircleGoodApproximation are very important. You'll likely need to experiment with the value of DistanceTolerance and RatioTolerance in IsCircleGoodApproximation to get accurate results for your specific parts. Lower values will be more sensitive and require a perfect circle. Higher values can generate false positives. You will need to find a balance based on your geometry.
GetNumberOfIsoCurves and GetIsoCurve Loop: The code now loops through each isocurve on the face. This improves the chance of finding a circular feature even if the face is not perfectly circular but has a circular section.
How to Use:
- Open CATIA V5.
- Open the part you want to analyze.
- Open the VBA editor (Tools -> Macro -> Visual Basic Editor).
- Insert a new module (Insert -> Module).
- Copy and paste the code into the module.
- Modify the
DistanceTolerance and RatioTolerance constants in the IsCircleGoodApproximation function to adjust the sensitivity of the circle detection. This is essential for good results.
- Run the macro (Run -> Run Sub/UserForm or press F5).
Important Considerations:
- Performance: This macro can be slow on complex parts with many faces.
- Accuracy: The accuracy of the results depends on the complexity of the faces and the tolerance values used. The
DistanceTolerance and RatioTolerance constants in the IsCircleGoodApproximation function need to be tuned based on the parts you are analyzing.
- False Positives: It's possible to get false positives (faces that are not truly circular but are detected as such). The
IsCircleGoodApproximation function is designed to minimize these, but you may need to adjust the tolerance values.
- Limitations: This macro may not work correctly on very complex surfaces or surfaces with irregular shapes. It also assumes that the circular features are generally planar. It will only find circular features lying on the surface of a face.
- Part structure: The code assumes the features are located in the
MainBody of the part. If the features are in other bodies, you will need to modify the code to loop through the appropriate bodies.
- Multi-body parts: If you are working with a multi-body part, you will need to modify the code to loop through each body in the part.
- Hidden faces: The code only analyzes visible faces. If you want to analyze hidden faces, you will need to modify the code to unhide them temporarily.
This improved version provides a much more reliable and accurate solution for finding circular features in CATIA V5 parts. Remember to adjust the tolerance values in the IsCircleGoodApproximation function to get the best results for your specific parts.