### Build C++ Examples with CMake and Makefiles Source: https://docs.cadexsoft.com/mtkpython/mtk_building_examples_cpp This snippet demonstrates how to build C++ examples using CMake and GNU Makefiles on Linux or MacOS. It outlines the directory structure, CMake commands for configuration and building, and environment variable setup for dynamic libraries. ```bash cd /dev/manufacturingtoolkit/1.0.0/examples/cxx/ mkdir build cmake -H. -Bbuild -G "Unix Makefiles" cmake --build build ``` -------------------------------- ### Build C++ Examples with CMake and Visual Studio Source: https://docs.cadexsoft.com/mtkpython/mtk_building_examples_cpp Instructions for building C++ examples on Windows using CMake and Microsoft Visual Studio. This involves using the cmake-gui to configure the project, selecting the Visual Studio generator, and then generating the solution files. ```bash # Example usage with cmake-gui (interactive) # 1. Open cmake-gui # 2. Specify example's subdirectory as source # 3. Choose a build directory # 4. Click 'Configure' # 5. Select Visual Studio version (e.g., 'Visual Studio 17 2019 Win64') # 6. Click 'Generate' # This creates Visual Studio project and solution files. ``` -------------------------------- ### Nesting Computer Example - C# Source: https://docs.cadexsoft.com/mtkpython/mtk_nesting_example Example implementation of the Nesting Computer in C#. ```C# // C# example code snippet would go here, referencing Program.cs ``` -------------------------------- ### Nesting Computer Example - Java Source: https://docs.cadexsoft.com/mtkpython/mtk_nesting_example Example implementation of the Nesting Computer in Java. ```Java // Java example code snippet would go here, referencing nesting_сomputer.java ``` -------------------------------- ### Nesting Computer Example - C++ Source: https://docs.cadexsoft.com/mtkpython/mtk_nesting_example Example implementation of the Nesting Computer in C++. ```C++ // C++ example code snippet would go here, referencing main.cxx ``` -------------------------------- ### Install MTK Web Library with npm Source: https://docs.cadexsoft.com/mtkpython/mtk_web_installation This code snippet shows how to install the MTK Web library using npm. It requires a provided URL from the Customer Corner. The installation adds the package to the project's dependencies. ```bash npm install ``` -------------------------------- ### Command-line Argument Parsing and Script Execution Source: https://docs.cadexsoft.com/mtkpython/exploring_2brep_topology_2brep_topology_8py-example Handles command-line arguments to get the input file path and initiates the main processing function. Includes usage instructions if the incorrect number of arguments is provided. ```python if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: " + os.path.abspath(Path(__file__).resolve()) + " , where:") print(" is a name of the file to be read") sys.exit(1) aSource = os.path.abspath(sys.argv[1]) sys.exit(main(aSource)) ``` -------------------------------- ### Set C++ Dynamic Library Path Source: https://docs.cadexsoft.com/mtkpython/mtk_building_examples_cpp This snippet shows how to set the environment variable to include the Manufacturing Toolkit dynamic libraries directory for running built examples. This is necessary for both Linux (LD_LIBRARY_PATH) and MacOS (DYLD_LIBRARY_PATH). ```bash # On Linux: # export LD_LIBRARY_PATH=/path/to/mtk/dynamic/libs:$LD_LIBRARY_PATH # On MacOS: # export DYLD_LIBRARY_PATH=/path/to/mtk/dynamic/libs:$DYLD_LIBRARY_PATH # Note: Replace /path/to/mtk/dynamic/libs with the actual path relevant to your installation, # considering target architecture, compiler, and mode (release/debug). ``` -------------------------------- ### B-Rep Topology Exploration Example in Java Source: https://docs.cadexsoft.com/mtkpython/mtk_brep_topology_example This Java code snippet is part of the B-Rep Topology Exploration example. It likely involves similar logic to the C++ and C# versions for navigating and analyzing B-Rep data, including bodies and shapes. ```java // Java equivalent for B-Rep Topology Exploration example ``` -------------------------------- ### B-Rep Topology Exploration Example in C# Source: https://docs.cadexsoft.com/mtkpython/mtk_brep_topology_example This C# code snippet is part of the B-Rep Topology Exploration example. It likely deals with accessing and processing B-Rep data structures, such as bodies and shapes, and potentially using shape comparison mechanisms similar to the C++ version. ```csharp // C# equivalent for B-Rep Topology Exploration example ``` -------------------------------- ### B-Rep Topology Exploration Example in Python Source: https://docs.cadexsoft.com/mtkpython/mtk_brep_topology_example This Python code snippet is part of the B-Rep Topology Exploration example. It provides a Pythonic way to interact with B-Rep data structures, likely involving methods for accessing parts, bodies, and shapes, and performing topological comparisons. ```python # Python equivalent for B-Rep Topology Exploration example ``` -------------------------------- ### C# Progress Bar Example for Manufacturing Toolkit Source: https://docs.cadexsoft.com/mtkpython/utilities_2progress_bar_2_program_8cs-example This C# code demonstrates how to use the `cadex::ProgressStatus` class to display progress during model reading and meshing operations. It requires a valid Manufacturing Toolkit license key and takes a file path as input. The `ProgressBarObserver` class customizes how progress updates are displayed. ```csharp using cadex; using cadex.ModelAlgo; using cadex.ModelData; using System; namespace progress_bar { class Program { static int Main(string[] args) { string aKey = MTKLicenseKey.Value(); // Activate the license (aKey must be defined in mtk_license.cs) if (!LicenseManager.Activate(aKey)) { Console.WriteLine("Failed to activate Manufacturing Toolkit license."); return 1; } // Get the input if (args.Length != 1) { Console.WriteLine("Usage: " + System.Reflection.Assembly.GetExecutingAssembly().Location + " , where:"); Console.WriteLine(" is a name of the file to be read"); return 1; } UTF16String aSource = new UTF16String(args[0]); // Observer must outlive ProgressStatus, // so it is created outside the using scope ProgressBarObserver anObserver = new ProgressBarObserver(); anObserver.SetAllNotifyingThreads(); Model aModel = new Model(); using (ProgressStatus aStatus = new ProgressStatus()) { // Register an Observer to progress status aStatus.Register(anObserver); // The top scope occupies the whole progress status range using (ProgressScope aTopScope = new ProgressScope(aStatus)) { // The remaining 50% of TopScope for reading using (ProgressScope aReaderScope = new ProgressScope(aTopScope, 50)) { ModelReader aReader = new ModelReader(); aReader.SetProgressStatus(aStatus); aReader.Read(aSource, aModel); } if (!aModel.IsEmpty() && !aStatus.WasCanceled()) { // The remaining 50% of TopScope for meshing using (ProgressScope aMesherScope = new ProgressScope(aTopScope, -1)) { MeshGenerator aMesher = new MeshGenerator(); // Connect progress status object aMesher.SetProgressStatus(aStatus); aMesher.Generate(aModel); } } } } return 0; } class ProgressBarObserver : ProgressStatus.Observer { public override void ChangedValue(ProgressStatus theInfo) { Console.WriteLine(theInfo.Value() + "% "); } public override void Completed(ProgressStatus theInfo) { Console.WriteLine(theInfo.Value() + "%: complete!"); } }; } } ``` -------------------------------- ### Python Projector Example Implementation Source: https://docs.cadexsoft.com/mtkpython/mtk_projector_example Implements a projector to create a 3D model projection and print its area. It uses mtk.ModelElementVoidVisitor to traverse parts and mtk.Projector_PolyProjector to perform the projection. The output includes the projection area for each part. Requires the mtk library. ```python class SceneGraphPolyProjector(mtk.ModelElementVoidVisitor): def __init__(self, theDirection: mtk.Direction): super().__init__() self.myDirection = theDirection self.myProjector = mtk.Projector_PolyProjector() def VisitPart(self, thePart: mtk.Part): aData = self.myProjector.Perform(thePart, self.myDirection) print(f"Part projection [{thePart.Name()}] has:") print(f" area = {aData.ProjectionArea()} mm\n") aProjector = SceneGraphPolyProjector(mtk.Direction.YDir()) aModel.Accept(aProjector) ``` -------------------------------- ### B-Rep Topology Exploration Example Source: https://docs.cadexsoft.com/mtkpython/mtk_brep_topology_example This example demonstrates how to explore topological entities within a B-Rep representation. It shows how to extract ModelData_Part from a ModelData_Model and then obtain ModelData_Body objects from each part. Each ModelData_Body contains ModelData_Shape objects, which can be iterated over to access shapes and their orientation. The example highlights the use of shape hashers and equality operations, including ModelData_OrientedShapeHash and ModelData_UnorientedShapeHash, and explains the difference between ModelData_Shape.IsEqual() and ModelData_Shape.IsSame(). ```c++ #define ShapesOrientationIsUsed 0 #if ShapesOrientationIsUsed typedef ModelData::OrientedShapeHash HasherType; typedef ModelData::OrientedShapeEqual EqualerType; #else typedef ModelData::UnorientedShapeHash HasherType; typedef ModelData::UnorientedShapeEqual EqualerType; #endif ``` -------------------------------- ### Analyze Wall Thickness - C# Source: https://docs.cadexsoft.com/mtkpython/mtk_wall_thickness_analyzer_example Performs wall thickness analysis on a 3D model using C#. This example demonstrates how to utilize the Cadexsoft MTK library in a C# environment. Input is a model file, and output includes thickness data. ```csharp /* Placeholder for C# code */ // using Cadexsoft.MTK; public class WallThicknessAnalyzer { public static void Main(string[] args) { // Load model // Analyze thickness // Display results } } ``` -------------------------------- ### Molding Feature Recognizer Example in Python Source: https://docs.cadexsoft.com/mtkpython/mtk_molding_feature_recognizer_example Demonstrates recognizing molding features on a 3D model and printing feature information to the console. It uses the Molding_FeatureRecognizer tool and requires an input file path as a command-line argument. The PartProcessor class, inherited from SolidProcessor, handles the recognition process. ```python import mtk import shape_processor class PartProcessor(shape_processor.SolidProcessor): def __init__(self): super().__init__() def ProcessSolid(self, theSolid: mtk.Solid): pass ``` -------------------------------- ### Python Nesting Computer Example Source: https://docs.cadexsoft.com/mtkpython/nesting_2nesting_computer_2nesting_computer_8java-example This Python script demonstrates the usage of the CADEX Manufacturing Toolkit for performing a nesting calculation. It configures nesting parameters, defines shapes (patterns), adds material, and executes the nesting process. It requires the 'CadExMTK' native library and a valid license key. ```python import cadex.* import cadex.Drawing.* import cadex.Geom.* import java.util.* public class nesting_computer { static { try { System.loadLibrary("CadExMTK"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load.\n" + e); System.exit(1); } } public static void main(String[] args) { String aKey = MTKLicenseKey.Value(); // Activate the license (aKey must be defined in MTKLicenseKey.java) if (!LicenseManager.Activate(aKey)) { System.out.println("Failed to activate Manufacturing Toolkit license."); System.exit(1); } Nesting_Computer aComputer = new Nesting_Computer(); // Configuring nesting parameters Nesting_ComputerParameters aParams = new Nesting_ComputerParameters(); aParams.SetIterationCount(10); // Number of iterations for optimization process aParams.SetGenerationSize(10); // Initial count of random layouts; larger values may improve optimization aParams.SetMutationRate(0.5); // Probability of random shape rearrangement to escape local optima aParams.SetPartToPartDistance(1.0); // Minimum distance between shapes aParams.SetPartToSheetBoundaryDistance(1.0); // Minimum distance between shapes and sheet edges aParams.SetMirrorControl(false); // Allows mirrored shapes to improve layout efficiency aParams.SetRotationCount(4); // Number of allowed rotation angles (e.g., 4 allows 0°, 90°, 180°, and 270°) aParams.SetCurveTolerance(10); // Side length of squares used for polygonal approximation of curves aComputer.SetParameters(aParams); // Define material size and number (e.g., 1 sheets of 100x100 mm) aComputer.AddMaterial(100.0, 100.0, 1); List aPatterns = Arrays.asList( new Pattern(CreateRectangle(50.0, 50.0), "Rectangle 50x50", 1), new Pattern(CreateRectangle(20.0, 10.0), "Rectangle 20x10", 10) ); PrintPatternsInfo(aPatterns); // Load patterns into the computer for (Pattern aPattern : aPatterns) { aComputer.AddPattern(aPattern.myDrawingView, aPattern.myNumber); } // Start the Nesting process Nesting_Data aData = aComputer.Perform(); // Print nesting information PrintNestingInfo(aData); } static class Pattern { public Pattern(CurveSet theShape, String theName, int theNumber) { myDrawingView.Add(theShape); myName = theName; myNumber = theNumber; } public View myDrawingView = new View(); public String myName; public int myNumber; } static CurveSet CreateRectangle(double theWidth, double theHeight) { CurveSet aRectangle = new CurveSet(); Line2d aL1 = new Line2d(new Point2d(0, 0), new Direction2d(1, 0)); aL1.SetTrim(0, theWidth); Line2d aL2 = new Line2d(new Point2d(theWidth, 0), new Direction2d(0, 1)); aL2.SetTrim(0, theHeight); Line2d aL3 = new Line2d(new Point2d(theWidth, theHeight), new Direction2d(-1, 0)); aL3.SetTrim(0, theWidth); Line2d aL4 = new Line2d(new Point2d(0, theHeight), new Direction2d(0, -1)); aL4.SetTrim(0, theHeight); aRectangle.AddCurve(aL1); aRectangle.AddCurve(aL2); aRectangle.AddCurve(aL3); aRectangle.AddCurve(aL4); return aRectangle; } } ``` -------------------------------- ### C# - Main Entry Point and License Activation Source: https://docs.cadexsoft.com/mtkpython/machining_2feature_recognizer_2_program_8cs-example The `Main` method in this C# program serves as the entry point for the Manufacturing Toolkit application. It handles license activation using `MTKLicenseKey` and `LicenseManager`, command-line argument parsing for input files and operations, and initiates the model loading and processing pipeline. This setup is essential for any application using the toolkit. ```csharp static int Main(string[] args) { string aKey = MTKLicenseKey.Value(); // Activate the license (the key should be defined in mtk_license.cs) if (!LicenseManager.Activate(aKey)) { Console.WriteLine("Failed to activate Manufacturing Toolkit license."); return 1; } if (args.Length != 2) { Console.WriteLine("Usage: " + $"{System.Reflection.Assembly.GetExecutingAssembly().Location} , where:"); Console.WriteLine($" is a name of the file to be read"); Console.WriteLine($" is a name of desired machining operation"); Console.WriteLine($""); PrintSupportedOperations(); return 1; } string aSource = args[0]; var aModel = new Model(); var aReader = new ModelReader(); // Reading the file if (!aReader.Read(new UTF16String(aSource), aModel)) { Console.WriteLine($"Failed to read the file {aSource}"); return 1; } Console.WriteLine($"Model: {aModel.Name()}\n"); string anOperationStr = args[1]; Machining_OperationType anOperation = OperationType(anOperationStr); if (anOperation == Machining_OperationType.Machining_OT_Undefined) { Console.WriteLine($"Unsupported operation - {anOperationStr}"); Console.WriteLine($"Please use one of the following."); PrintSupportedOperations(); return 1; } var aPartProcessor = new PartProcessor(anOperation); var aVisitor = new ModelElementUniqueVisitor(aPartProcessor); aModel.Accept(aVisitor); return 0; } ``` -------------------------------- ### Set up Recognizer and Perform Feature Recognition in Python Source: https://docs.cadexsoft.com/mtkpython/mtk_molding_feature_recognizer_example Initializes Molding_FeatureRecognizerParameters, sets parameters like MaxRibThickness and MaxRibDraftAngle, creates a Molding_FeatureRecognizer, and performs feature recognition on a given solid model. The output is a list of recognized features. ```python aRecognizerParameters = mtk.Molding_FeatureRecognizerParameters() aRecognizerParameters.SetMaxRibThickness (30.0) aRecognizerParameters.SetMaxRibDraftAngle (0.2) aRecognizerParameters.SetMaxRibTaperAngle (0.1) aRecognizer = mtk.Molding_FeatureRecognizer(aRecognizerParameters) aFeatureList = aRecognizer.Perform (theSolid) PrintFeatures(aFeatureList) ``` -------------------------------- ### DiametricDimension Class Source: https://docs.cadexsoft.com/mtkpython/classmanufacturingtoolkit_1_1_cad_ex_m_t_k_1_1_drawing___diametric_dimension Documentation for the DiametricDimension class, which represents a diametric dimension in a drawing. It includes methods for setting and getting dimension points, checking if the dimension starts from the center, and other related properties. ```APIDOC ## manufacturingtoolkit.CadExMTK.Drawing_DiametricDimension ### Description Represents a diametric dimension in a drawing. This class allows for the creation and manipulation of diametric dimensions, including setting measurement points and properties. ### Methods #### Constructor `__init__(self, *args)` - Description: Initializes a new instance of the DiametricDimension class. #### First Chord Point - `FirstChordPoint(self)` - Description: Returns the first chord point of the diametric dimension. - Method: GET - `SetFirstChordPoint(self, theFirstChordPoint)` - Description: Sets the first chord point of the diametric dimension. - Method: SET - Parameters: - `theFirstChordPoint` (Point) - The first chord point. #### Second Chord Point - `SecondChordPoint(self)` - Description: Returns the second chord point of the diametric dimension. - Method: GET - `SetSecondChordPoint(self, theSecondChordPoint)` - Description: Sets the second chord point of the diametric dimension. - Method: SET - Parameters: - `theSecondChordPoint` (Point) - The second chord point. #### Dimension End Point - `DimensionEndPoint(self)` - Description: Returns the dimension end point. - Method: GET - `SetDimensionEndPoint(self, theDimensionEndPoint)` - Description: Sets the dimension end point. - Method: SET - Parameters: - `theDimensionEndPoint` (Point) - The dimension end point. #### Starts From Center - `StartsFromCenter(self)` - Description: Returns true if the dimension line passes through the center of the measured entity. - Method: GET - `SetStartsFromCenter(self, theStartsFromCenter)` - Description: Sets whether the dimension line passes through the center of the measured entity. - Method: SET - Parameters: - `theStartsFromCenter` (bool) - True if the dimension starts from the center, false otherwise. ### Inherited Methods from manufacturingtoolkit.CadExMTK.Drawing_Dimension - `SetFirstArrowType(self, theFirstArrowType)`: Sets type of the first arrow of dimension. - `SecondArrowType(self)`: Returns type of the second arrow of dimension. - `SetSecondArrowType(self, theSecondArrowType)`: Sets type of the second arrow of dimension. - `ArrowheadPlacement(self)`: Returns the arrowhead placement. - `SetArrowheadPlacement(self, theArrowheadPlacement)`: Sets the arrowhead placement. - `AlignTextHorizontally(self)`: Returns true if the measurement text is align horizontally. - `SetAlignTextHorizontally(self, theAlignTextHorizontally)`: Sets the text alignment to horizontal. - `MeasurementValue(self)`: Returns the actual measurement. - `SetMeasurementValue(self, theMeasurementValue)`: Sets the actual measurement. - `Text(self)`: Returns the dimension text. - `SetText(self, theText)`: Sets the dimension text. ### Inherited Methods from manufacturingtoolkit.CadExMTK.Drawing_Element - `SetUuid(self, theUuid)`: Sets the unique identifier for the element. - `Uuid(self)`: Returns the unique identifier of the element. - `Accept(self, theVisitor)`: Accepts a visitor for processing. ### Inherited Methods from manufacturingtoolkit.CadExMTK.BaseObject - `Id(self)`: Return unique identifier of public object. - `IsNull(self)`: Checks if the object is null. - `IsEqual(self, theObj)`: Checks if this object is equal to another object. - `__hash__(self)`: Returns the hash value of the object. - `__eq__(self, other)`: Checks for equality with another object. ### Static Public Member Functions - `CompareType(theObject)` (inherited from `manufacturingtoolkit.CadExMTK.Drawing_Dimension`): Compares the type of the given object. - `Cast(theBase)` (inherited from `manufacturingtoolkit.CadExMTK.Drawing_Dimension`): Casts a base object to a DiametricDimension object. ``` -------------------------------- ### Progress Bar Example Source: https://docs.cadexsoft.com/mtkpython/utilities_2progress_bar_2main_8cxx-example Demonstrates how to use ProgressStatus and ProgressScope to monitor and display the progress of operations like model reading and meshing. It requires license activation and takes an input file path as a command-line argument. ```cpp #include #include #include #include #include #include #include #include "../../mtk_license.cxx" using namespace std; using namespace cadex; class ProgressBarObserver : public ProgressStatus::Observer { public: void ChangedValue (const ProgressStatus& theInfo) override { cout << theInfo.Value() << "%" << endl; } void Completed (const ProgressStatus& theInfo) override { cout << theInfo.Value() << "%: complete!" << endl; } }; int main (int argc, char* argv[]) { auto aKey = MTKLicenseKey::Value(); // Activate the license (aKey must be defined in mtk_license.cxx) if (!CADExLicense_Activate (aKey)) { cerr << "Failed to activate Manufacturing Toolkit license." << endl; return 1; } // Get the input if (argc != 2) { cerr << "Usage: " << argv[0] << " , where:" << endl; cerr << " is a name of the file to be read" << endl; return 1; } const char* aSource = argv[1]; // Create observer // An observer must have a greater life span than aStatus // so create it in explicit external scope for aStatus ProgressBarObserver anObserver; anObserver.SetAllNotifyingThreads(); ModelData::Model aModel; // Register an Observer to progress status ProgressStatus aStatus; aStatus.Register (anObserver); // The top scope occupies the whole progress status range ProgressScope aTopScope (aStatus); { // The remaining 50% of TopScope for reading ProgressScope aReaderScope (aTopScope, 50); ModelData::ModelReader aReader; aReader.SetProgressStatus (aStatus); aReader.Read (aSource, aModel); } // The remaining 50% of TopScope for meshing if (!aModel.IsEmpty() && !aStatus.WasCanceled()) { ProgressScope aMesherScope (aTopScope, 50); ModelAlgo::MeshGenerator aMesher; // Connect progress status object aMesher.SetProgressStatus (aStatus); aMesher.Generate (aModel); } return 0; } ``` -------------------------------- ### Enable Exception Support in C++ Compilers Source: https://docs.cadexsoft.com/mtkpython/mtk_building_examples_cpp This snippet highlights the compiler flags required to enable exception support for proper handling within the Manufacturing Toolkit. It specifies flags for MSVC, Clang, and GCC. ```bash # MSVC: # /EHa or /EHsc # Clang and GCC: # -fexceptions ``` -------------------------------- ### Load and Activate CADEX Manufacturing Toolkit Source: https://docs.cadexsoft.com/mtkpython/molding_2dfm_analyzer_2dfm_analyzer_8java-example This snippet demonstrates the initial setup for using the CADEX Manufacturing Toolkit. It involves loading the native library and activating the license using a provided key. Error handling is included for license activation and library loading. ```Java import cadex.*; import cadex.ModelData.*; import java.util.Map; import java.util.HashMap; import java.util.function.Consumer; public class dfm_analyzer { static { try { System.loadLibrary("CadExMTK"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load.\n" + e); System.exit(1); } } public static void main(String[] args) { String aKey = MTKLicenseKey.Value(); // Activate the license (the key must be defined in MTKLicenseKey.java) if (!LicenseManager.Activate(aKey)) { System.out.println("Failed to activate Manufacturing Toolkit license."); System.exit(1); } // ... rest of the main method ... } // ... rest of the class ... } ``` -------------------------------- ### Wall Thickness Analysis Example (Python) Source: https://docs.cadexsoft.com/mtkpython/mtk_wall_thickness This Python code snippet demonstrates how to use the WallThickness_Analyzer to perform a wall thickness analysis on a solid model. It initializes the analyzer, sets a resolution, and calls the Perform method to get wall thickness data. The modelData_Solid object is assumed to be pre-defined. ```Python # Wall Thickness Calculation Example # Assume aSolid is a pre-defined mtk.ModelData_Solid object aSolid = ... anAnalyzer = mtk.WallThickness_Analyzer() aResolution = 800 # Perform the analysis with a specified resolution aData = anAnalyzer.Perform(aSolid, aResolution) # The 'aData' object now contains WallThickness_Data with min and max thicknesses. # You can access these values, for example: # min_thickness = aData.GetMinThickness() # max_thickness = aData.GetMaxThickness() ``` -------------------------------- ### C# Manufacturing Toolkit: License Activation and File Loading Source: https://docs.cadexsoft.com/mtkpython/machining_2dfm_analyzer_2_program_8cs-example This C# code demonstrates the entry point for the Manufacturing Toolkit application. It handles license activation using `MTKLicenseKey` and `LicenseManager`, parses command-line arguments for input file and operation, and reads the model using `ModelReader`. It includes basic error handling for license activation and file reading. Dependencies include `cadex`, `cadex.ModelData`, `feature_group`, `shape_processor`, and `System` namespaces. ```csharp using cadex; using cadex.ModelData; using feature_group; using shape_processor; using System; using System.Collections.Generic; namespace dfm_analyzer { class Program { static int Main(string[] args) { string aKey = MTKLicenseKey.Value(); // Activate the license (the key should be defined in mtk_license.cs) if (!LicenseManager.Activate(aKey)) { Console.WriteLine("Failed to activate Manufacturing Toolkit license."); return 1; } if (args.Length != 2) { Console.WriteLine("Usage: " + $"{System.Reflection.Assembly.GetExecutingAssembly().Location} , where:"); Console.WriteLine($" is a name of the file to be read"); Console.WriteLine($" is a name of desired machining operation"); Console.WriteLine($""); PrintSupportedOperations(); return 1; } string aSource = args[0]; var aModel = new Model(); var aReader = new ModelReader(); // Reading the file if (!aReader.Read(new UTF16String(aSource), aModel)) { Console.WriteLine($"Failed to read the file {aSource}"); return 1; } Console.WriteLine($"Model: {aModel.Name()}\n"); string anOperationStr = args[1]; Machining_OperationType anOperation = OperationType(anOperationStr); if (anOperation == Machining_OperationType.Machining_OT_Undefined) { Console.WriteLine($"Unsupported operation - {anOperationStr}"); Console.WriteLine($"Please use one of the following."); PrintSupportedOperations(); return 1; } var aPartProcessor = new PartProcessor(anOperation); var aVisitor = new ModelElementUniqueVisitor(aPartProcessor); aModel.Accept(aVisitor); return 0; } class PartProcessor : SolidProcessor { public PartProcessor(Machining_OperationType theOperation) { myOperation = theOperation; } public override void ProcessSolid(Solid theSolid) { // Find features var aData = new Machining_Data(); var aParam = new Machining_FeatureRecognizerParameters(); aParam.SetOperation(myOperation); var aRecognizer = new Machining_FeatureRecognizer(aParam); aRecognizer.Perform(theSolid, aData); ``` -------------------------------- ### C++ Main Application Entry Point and License Activation Source: https://docs.cadexsoft.com/mtkpython/_m_t_k_converter_2main_8cxx-example This C++ snippet is the main entry point for the MTKConverter application. It initializes and activates the CADEX license using a key defined in `mtk_license.cxx`. If license activation fails, it prints an error and exits. It then creates an instance of `MTKConverter_Application` and calls its `Run` method to start the application's main loop. ```cpp #include #include #include #include "../../mtk_license.cxx" using namespace cadex; using namespace std; int main (int argc, char* argv[]) { auto aKey = MTKLicenseKey::Value(); // Activate the license (aKey must be defined in mtk_license.cxx) if (!CADExLicense_Activate (aKey)) { cerr << "Failed to activate Manufacturing Toolkit license." << endl; return 1; } MTKConverter_Application anApp; return anApp.Run (argc, argv); } ``` -------------------------------- ### Mesh Generation and Face Triangulation Example (C++) Source: https://docs.cadexsoft.com/mtkpython/meshing_2mesh_generation_2main_8cxx-example This C++ code demonstrates how to use the Manufacturing Toolkit to read a CAD model, generate a mesh, and then extract and print triangulation information for the first face found in the model. It includes license activation, model reading, mesh parameter setup, and face traversal. ```C++ #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include #include #include #include #include #include #include #include #include #include #include "../../mtk_license.cxx" using namespace std; using namespace cadex; class FirstFaceGetter : public ModelData::ModelElementVoidVisitor { public: void operator() (const ModelData::Part& thePart) override { if (myFace.IsNull()) { ExploreBRep (thePart.Bodies()); } } const ModelData::Face& FirstFace() { return myFace; }; private: void ExploreBRep (const std::vector& theBodies) { for (const auto& aBody : theBodies) { ModelData::ShapeIterator aFaceIt (aBody, ModelData::ShapeType::Face); if (aFaceIt.HasNext()) { const auto& aFirstShape = aFaceIt.Next(); const auto& aFirstFace = ModelData::Face::Cast (aFirstShape); myFace = aFirstFace; break; } } }; ModelData::Face myFace; }; void PrintFaceTriangulationInfo (const ModelData::Face& theFace) { ModelData::IndexedTriangleSet anITS = theFace.Triangulation(); cout << "Face triangulation contains " << anITS.NumberOfTriangles() << " triangles." << endl; const size_t aNumberOfTrianglesToPrint = std::min (size_t (4), anITS.NumberOfTriangles()); for (size_t i = 0; i < aNumberOfTrianglesToPrint; ++i) { cout << "Triangle index " << i << " with vertices: " << endl; for (size_t j = 0; j < 3; ++j) { auto aVertexIndex = anITS.TriangleVertexIndex (i, j); cout << " Vertex index " << aVertexIndex << " with coords (" ; auto aPoint = anITS.TriangleVertex (i, j); cout << "X: " << aPoint.X() << ", "; cout << "Y: " << aPoint.Y() << ", "; cout << "Z: " << aPoint.Z() << ")" << endl; } } } int main (int argc, char* argv[]) { auto aKey = MTKLicenseKey::Value(); // Activate the license (aKey must be defined in mtk_license.cxx) if (!CADExLicense_Activate (aKey)) { cerr << "Failed to activate Manufacturing Toolkit license." << endl; return 1; } if (argc != 2) { cerr << "Usage: " << argv[0] << " , where:" << endl; cerr << " is a name of the file to be read" << endl; return 1; } const char* aSource = argv[1]; ModelData::Model aModel; ModelData::ModelReader aReader; if (!aReader.Read (aSource, aModel)) { cerr << "Failed to read the file " << aSource << endl; return 1; } // Set up mesher and parameters: ModelAlgo::MeshGeneratorParameters aParam; aParam.SetAngularDeflection (M_PI * 10 / 180); aParam.SetChordalDeflection (0.003); ModelAlgo::MeshGenerator aMesher (aParam); aMesher.Generate (aModel); FirstFaceGetter aVisitor; aModel.Accept (aVisitor); ModelData::Face aFace = aVisitor.FirstFace(); PrintFaceTriangulationInfo (aFace); return 0; } ``` -------------------------------- ### Initialize Manufacturing Toolkit Application and Load Libraries in Java Source: https://docs.cadexsoft.com/mtkpython/_m_t_k_converter_2_m_t_k_converter_8java-example This code snippet demonstrates the initialization process for the Manufacturing Toolkit application. It includes loading necessary native libraries ('CadExMTK' and 'MTKView') and activating the license using a provided key. If library loading fails, it prints an error and exits. ```java import cadex.*; public class MTKConverter { static { try { System.loadLibrary("CadExMTK"); System.loadLibrary("MTKView"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load.\n" + e); System.exit(1); } } public static void main(String[] args) { String aKey = MTKLicenseKey.Value(); // Activate the license (the key must be defined in MTKLicenseKey.java) if (!LicenseManager.Activate(aKey)) { System.out.println("Failed to activate Manufacturing Toolkit license."); System.exit(1); } MTKConverter_Application anApp = new MTKConverter_Application(); System.exit(anApp.Run(args).GetValue()); } } ``` -------------------------------- ### Load and Traverse B-Rep Geometry using Java Source: https://docs.cadexsoft.com/mtkpython/exploring_2brep_geometry_2brep_geometry_8java-example This Java code snippet demonstrates initializing the Manufacturing Toolkit, activating the license, reading a model file, and then traversing the B-Rep geometry using a visitor pattern. It requires the CADEX libraries and a valid license key. ```java import cadex.*; import cadex.ModelData.*; public class brep_geometry { static { try { System.loadLibrary("CadExMTK"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load.\n" + e); System.exit(1); } } public static void main(String[] args) { String aKey = MTKLicenseKey.Value(); // Activate the license (the key must be defined in MTKLicenseKey.java) if (!LicenseManager.Activate(aKey)) { System.out.println("Failed to activate Manufacturing Toolkit license."); System.exit(1); } if (args.length != 1) { System.out.println("Usage: " + " , where:"); System.out.println(" is a name of the file to be read"); System.exit(1); } String aSource = args[0]; Model aModel = new Model(); if (!new ModelReader().Read(new UTF16String(aSource), aModel)) { System.out.println("Failed to read the file"); System.exit(1); } shape_explorer aVisitor = new shape_explorer(); aModel.Accept(aVisitor); } } ``` -------------------------------- ### Main Execution Entry Point Source: https://docs.cadexsoft.com/mtkpython/sheet_metal_2unfolder_2main_8cxx-example The main function initializes the Manufacturing Toolkit, activates the license, parses command-line arguments for input file and output folder, reads the model, and initiates the model processing using a visitor pattern. ```cpp int main (int argc, char* argv[]) { auto aKey = MTKLicenseKey::Value(); // Activate the license (aKey must be defined in mtk_license.cxx) if (!CADExLicense_Activate (aKey)) { cerr << "Failed to activate Manufacturing Toolkit license." << endl; return 1; } if (argc != 3) { cerr << "Usage: " << argv[0] << " , where:" << endl; cerr << " is a name of the file to be read" << endl; cerr << " is a name of the folder where DXF files with drawing to be written" << endl; return 1; } const char* aSource = argv[1]; const char* aDrawingPath = argv[2]; ModelData::Model aModel; ModelData::ModelReader aReader; // Reading the file if (!aReader.Read (aSource, aModel)) { cerr << "Failed to read the file " << aSource << endl; return 1; } cout << "Model: " << aModel.Name() << "\n" << endl; //processing PartProcessor aPartProcessor (aDrawingPath); ModelData::ModelElementUniqueVisitor aVisitor (aPartProcessor); aModel.Accept (aVisitor); return 0; } ``` -------------------------------- ### Application Entry Point and Argument Parsing Source: https://docs.cadexsoft.com/mtkpython/_m_t_k_converter_2main_8cxx-example Defines the constructor for MTKConverter_Application and its Run method, which serves as the application's entry point. It handles command-line arguments, including help requests and validation of the number of arguments, before proceeding with mode selection and initialization for model processing. ```cpp MTKConverter_Application::MTKConverter_Application() { } MTKConverter_ReturnCode MTKConverter_Application::Run (int argc, char *argv[]) const { if (argc == 1 || ( !strcmp (argv[1], "-?") || !strcmp (argv[1], "/?") || !strcmp (argv[1], "-h") || !strcmp (argv[1], "--help"))) { PrintUsage(); return MTKConverter_RC_OK; } if (argc < 6) { std::cerr << "Invalid number of arguments. Please use \"-h\" or \"--help\" for usage information." << std::endl; return MTKConverter_RC_InvalidArgumentsNumber; } //parse and execute command line enum Mode { NeutralMode, ImportMode, ProcessMode, ExportMode }; ModelData::Model aModel; ModelData::Model aProcessModel; auto aMode = NeutralMode; MTKConverter_Report aReport; auto aRes = MTKConverter_RC_OK; bool aToGenerateScreenshot = true; ``` -------------------------------- ### React: Viewport Component Source: https://docs.cadexsoft.com/mtkpython/mtk_web_examples_react_base_model_viewer Initializes the canvas element for rendering the 3D scene. It utilizes the `react-three-fiber` library's Canvas component to set up the WebGL context and render the scene graph. The `orthographic` and `frameloop='demand'` props configure the camera and rendering behavior. It includes a ViewportInitializer component to manage the scene setup. ```typescript import { Canvas } from '@react-three/fiber'; import { ViewportInitializer } from './ViewportInitializer'; // Assuming this import interface ViewportProps { viewportRef: any; // Replace 'any' with a more specific type if available } export const Viewport = (props: ViewportProps) => { // The actual viewport logic and scene setup is handled within ViewportInitializer // and potentially the viewportRef object passed to it. return ( ); }; ``` -------------------------------- ### Activate Manufacturing Toolkit License and Run Application (C#) Source: https://docs.cadexsoft.com/mtkpython/_m_t_k_converter_2_program_8cs-example This C# code snippet demonstrates the initialization process for the Manufacturing Toolkit. It includes activating the software license using a provided key and then running the main converter application. The snippet handles potential license activation failures by printing an error message and exiting. ```C# using cadex; using System; namespace mtkconverter { class Program { static int Main(string[] args) { string aKey = MTKLicenseKey.Value(); // Activate the license (aKey should be defined in mtk_license.cs) if (!LicenseManager.Activate(aKey)) { Console.WriteLine("Failed to activate Manufacturing Toolkit license."); return 1; } MTKConverter_Application anApp = new MTKConverter_Application(); return (int)anApp.Run(args); } } } ``` -------------------------------- ### Use Molding_Analyzer for Feature Recognition (Python) Source: https://docs.cadexsoft.com/mtkpython/mtk_molding_recognition This example illustrates using the Molding_Analyzer to perform multiple recognition tools, starting with Molding_FeatureRecognizer. It shows how to add the recognizer to the analyzer, execute the analysis on a solid model, and then access the collected feature data from the resulting Molding_Data object. This approach allows for consolidated data processing. ```Python # Assume 'aSolid' is a defined mtk.Solid object aSolid = ... # Replace with actual solid model initialization # Initialize the Molding Analyzer anAnalyzer = mtk.Molding_Analyzer() # Add the Molding_FeatureRecognizer tool to the analyzer anAnalyzer.AddTool(mtk.Molding_FeatureRecognizer()) # Perform the analysis on the solid model aData = anAnalyzer.Perform(aSolid) # Retrieve the list of features from the analysis results aFeatures = aData.FeatureList() # 'aFeatures' now holds the recognized features collected by the analyzer. ``` -------------------------------- ### Transform Curve Operations (Python Example) Source: https://docs.cadexsoft.com/mtkpython/classmanufacturingtoolkit_1_1_cad_ex_m_t_k_1_1_geom___curve Illustrates various transformation operations that can be applied to a curve, such as translation, rotation, mirroring, scaling, and arbitrary matrix transformation. It also shows how to get a reversed orientation of the curve. Note that methods ending in 'd' (e.g., Transformed) return a modified copy, preserving the original curve. ```python from manufacturingtoolkit.CadExMTK import Geom_Curve, Geom_Vector3D, Geom_Matrix4x4 # Assuming aLine is an instance of a curve subclass # aLine = ... # Translation translated_line = aLine.Translated(Geom_Vector3D(1.0, 2.0, 3.0)) # Rotation (example: rotate 90 degrees around Z-axis) rotated_line = aLine.Rotated(Geom_Vector3D(0.0, 0.0, 1.0), 90.0) # Mirroring mirrored_line = aLine.Mirrored(Geom_Vector3D(1.0, 0.0, 0.0)) # Mirror across YZ plane # Scaling scaled_line = aLine.Scaled(2.0) # Scale by factor of 2 # Arbitrary transformation using a 3x4 matrix # matrix = Geom_Matrix4x4(...) # transformed_line = aLine.Transformed(matrix) # Reversed orientation reversed_line = aLine.Reversed() # In-place modification (use with caution, affects other users) # aLine.Translate(Geom_Vector3D(1.0, 2.0, 3.0)) ``` -------------------------------- ### Activate License and Read Model in Python Source: https://docs.cadexsoft.com/mtkpython/projector_2poly_projector_2poly_projector_8java-example This snippet shows how to activate the Manufacturing Toolkit license and read a model from a file using Python. It includes error handling for license activation and file reading. The input is a file path, and the output is a loaded CADEX model or an error message. ```java import cadex.*; import cadex.ModelData.*; import java.util.*; public class poly_projector { static { try { System.loadLibrary("CadExMTK"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load.\n" + e); System.exit(1); } } public static void main(String[] args) { String aKey = MTKLicenseKey.Value(); // Activate the license (the key must be defined in MTKLicenseKey.java) if (!LicenseManager.Activate(aKey)) { System.out.println("Failed to activate Manufacturing Toolkit license."); System.exit(1); } if (args.length != 1) { System.out.println("Usage: " + " , where:"); System.out.println(" is a name of the file to be read"); System.exit(1); } String aSource = args[0]; Model aModel = new Model(); ModelReader aReader = new ModelReader(); // Reading the file if (!aReader.Read(new UTF16String(aSource), aModel)) { System.out.println("Failed to read the file " + aSource); System.exit(1); } System.out.format("Model: %s\n\n", aModel.Name()); ModelPolyProjector aProjector = new ModelPolyProjector(cadex.Geom.Direction.YDir()); aModel.Accept(aProjector); } } class ModelPolyProjector extends ModelElementVoidVisitor { public ModelPolyProjector(cadex.Geom.Direction theDirection) { myDirection = theDirection; } @Override public void Apply(Part thePart) { Projector_PolyData aData = myProjector.Perform(thePart, myDirection); System.out.println("Part projection [" + thePart.Name() + "] has:"); System.out.println(" area = " + aData.ProjectionArea() + " mm"); } private cadex.Geom.Direction myDirection; private Projector_PolyProjector myProjector = new Projector_PolyProjector(); } ``` -------------------------------- ### Analyze Wall Thickness - Java Source: https://docs.cadexsoft.com/mtkpython/mtk_wall_thickness_analyzer_example Demonstrates wall thickness analysis using Java and the Cadexsoft MTK. The code loads a specified model file and calculates thickness parameters, outputting the results. ```java /* Placeholder for Java code */ // import com.cadexsoft.mtk.*; public class Analyzer { public static void main(String[] args) { // Load model file // Call MTK for analysis // Print thickness info } } ```