### Set and Get Document File Name using KGAX1.DocumenFileName and KGAX1.SetDocumenFileName Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1434.txt This C code example demonstrates setting and retrieving the file name of a Kompas document associated with an object, likely KGAX1. It shows direct property assignment (KGAX1.DocumenFileName) and the use of dedicated methods (KGAX1.SetDocumenFileName and KGAX1.GetDocumenFileName). Note: The example shows duplicated code for setting and getting the file name. ```c KGAX1.DocumenFileName = "С:\\1.frw"; (* ) fileName = KGAX1.DocumenFileName; (* ) KGAX1.SetDocumenFileName ("С:\\1.frw"); (**) fileName = KGAX1.GetDocumenFileName(); (**) ``` -------------------------------- ### Set and Get Caption using KGAX1.Caption and KGAX1.SetCaption Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1434.txt This C code demonstrates setting and getting the caption of an object, presumably a Kompas graphical element represented by KGAX1. It shows direct property assignment (KGAX1.Caption) and method calls (KGAX1.SetCaption and KGAX1.GetCaption). ```c KGAX1.Caption = "Заголовок"; (* ) Caption = KGAX1.Caption; (* ) KGAX1.SetCaption("Заголовок"); (**) Caption = KGAX1.GetCaption(); (**) ``` -------------------------------- ### Manage Progress Bar Indicator (COM) Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_029.txt This snippet demonstrates how to manage a progress bar using the COM interface of IProgressBarIndicator. It includes methods to start, set progress and text, and stop the indicator. Ensure the indicator is started before setting progress and stopped upon completion. ```COM HRESULT SetProgress (long currentVal, BSTR newText, VARIANT_BOOL resetText); HRESULT SetText (BSTR newText); HRESULT Start (long minVal, long maxVal, BSTR newText, VARIANT_BOOL resetText); void Stop (LPCTSTR newText, BOOL resetTxt); ``` -------------------------------- ### Implement Library with Custom Dialog in C++ Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Details how to create a custom dialog for user input within a KOMPAS library plugin using MFC. It defines a dialog class with data exchange and shows how to instantiate and display the dialog to get parameters for creating a bolt. Requires MFC and KOMPAS API typelib. ```cpp #include class CBoltDialog : public CDialog { public: double diameter; double length; int threadType; protected: virtual void DoDataExchange(CDataExchange* pDX) { DDX_Text(pDX, IDC_DIAMETER, diameter); DDX_Text(pDX, IDC_LENGTH, length); DDX_CBIndex(pDX, IDC_THREAD_TYPE, threadType); } }; void CreateBolt(IApplicationPtr pApp) { // Get KOMPAS main window HWND hKompas = (HWND)pApp->GetHWindow(); CWnd parent; parent.Attach(hKompas); CBoltDialog dlg; dlg.diameter = 10.0; dlg.length = 50.0; if (dlg.DoModal() == IDOK) { // Create bolt with parameters IDocumentsPtr pDocs = pApp->Documents; IKompasDocumentPtr pDoc = pDocs->Add(ksDocumentPart, VARIANT_TRUE); IPart7Ptr pPart = pDoc->RootPart; // Build parametric bolt... CreateBoltGeometry(pPart, dlg.diameter, dlg.length, dlg.threadType); } parent.Detach(); } ``` -------------------------------- ### Progress Bar for Long Operations in C++ Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Illustrates how to implement a progress bar to provide user feedback during lengthy batch operations. This involves starting, updating, and stopping the progress indicator, showing the status of operations like file processing. ```cpp IProgressBarIndicatorPtr pProgress = pApp->ProgressBarIndicator; int totalFiles = 100; pProgress->Start(0, totalFiles, "Processing files...", VARIANT_TRUE); for (int i = 0; i < totalFiles; i++) { // Process file IKompasDocumentPtr pDoc = pDocs->Open(filenames[i], VARIANT_FALSE); // Perform operation ProcessDocument(pDoc); // Update progress char status[256]; sprintf(status, "Processing: %s", filenames[i]); pProgress->SetProgress(i + 1, status, VARIANT_FALSE); pDoc->Close(ksDocumentCloseOptions::kdcSaveChanges); } pProgress->Stop("Processing complete", VARIANT_TRUE); ``` -------------------------------- ### IProgressBarIndicator Methods Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_029.txt Methods for controlling the progress indicator, including starting, stopping, setting progress values, and updating text. ```APIDOC ## IProgressBarIndicator ### Description Provides functionality to start, set progress, stop the progress indicator, and set status bar text. ### Methods #### SetProgress ##### Description Sets the current value of the progress indicator and optionally updates the status bar text. ##### Syntax (Automation) `void SetProgress(long currentVal, LPCTSTR newText, BOOL resetText);` ##### Syntax (COM) `HRESULT SetProgress(long currentVal, BSTR newText, VARIANT_BOOL resetText);` ##### Parameters - **currentVal** (long) - The current value of the indicator. - **newText** (LPCTSTR/BSTR) - The text to display in the status bar. - **resetText** (BOOL/VARIANT_BOOL) - TRUE to update the status bar text. ##### Note This method only works if the progress indicator has been started with `Start`. #### SetText ##### Description Sets the text in the status bar of the progress indicator. ##### Syntax (Automation) `void SetText(LPCTSTR newText);` ##### Syntax (COM) `HRESULT SetText(BSTR newText);` ##### Parameters - **newText** (LPCTSTR/BSTR) - The text to display in the status bar. ##### Note This method can be called whether the indicator is running or stopped. If called while running, the text is remembered and displayed upon stopping. If called while stopped, the text is displayed immediately. #### Start ##### Description Starts the progress indicator with specified minimum and maximum values, and initial text. ##### Syntax (Automation) `void Start(long minVal, long maxVal, LPCTSTR newText, BOOL resetText);` ##### Syntax (COM) `HRESULT Start(long minVal, long maxVal, BSTR newText, VARIANT_BOOL resetText);` ##### Parameters - **minVal** (long) - The minimum value of the scale. - **maxVal** (long) - The maximum value of the scale. - **newText** (LPCTSTR/BSTR) - The initial text to display in the status bar. - **resetText** (BOOL/VARIANT_BOOL) - TRUE to update the status bar text. ##### Note After finishing, the progress indicator should be stopped using the `Stop` method. #### Stop ##### Description Stops the progress indicator. ##### Syntax (Automation) `void Stop(LPCTSTR newText, BOOL resetTxt);` ##### Note Allows setting final text and whether to reset text upon stopping. The exact COM equivalent signature is not provided in the input. ``` -------------------------------- ### C++: Get Instance Count and Display Message Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1377.txt This snippet demonstrates how to get the total instance count of components using GetInstanceCount and display it using the Message function. It utilizes C++ with COM variants. ```cpp long count = topPart">GetInstanceCount( NULL ); // Общее количество компонентов Message( _bstr_t( count) ); ``` -------------------------------- ### Set and Get Text using KGAX1.Text and KGAX1.SetText Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1434.txt This C code illustrates how to set and retrieve the text content of an object, likely a Kompas graphical element identified as KGAX1. It covers both direct property access (KGAX1.Text) and the use of setter/getter methods (KGAX1.SetText and KGAX1.GetText). ```c KGAX1.Text = "Заголовок"; (* ) Text = KGAX1.Text; (* ) KGAX1.SetText ("Заголовок"); (**) Text = KGAX1.GetText(); (**) ``` -------------------------------- ### Set and Get 3D Wireframe Shaded Mode using KGAX1.Document3DWireframeShadedMode and KGAX1.SetDocument3DWireframeShadedMode Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1434.txt This C code example demonstrates how to set and get the 3D wireframe shaded mode for a Kompas document object, likely KGAX1. It uses direct property assignment (KGAX1.Document3DWireframeShadedMode) and corresponding setter/getter methods. ```c KGAX1.Document3DWireframeShadedMode = TRUE; (* ) Mode = KGAX1.Document3DWireframeShadedMode; (* ) KGAX1.SetDocument3DWireframeShadedMode (TRUE); (**) KGAX1.GetDocument3DWireframeShadedMode(); (**) ``` -------------------------------- ### Manage Progress Bar Indicator (Automation) Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_029.txt This snippet shows how to manage a progress bar using the Automation interface of IProgressBarIndicator. It covers starting the indicator with minimum and maximum values, setting current progress and text, and stopping the indicator. The SetText method can be used independently of the indicator's running state. ```Automation void SetProgress (long currentVal, LPCTSTR newText, BOOL resetText); void SetText (LPCTSTR newText); void Start (long minVal, long maxVal, LPCTSTR newText, BOOL resetText); void Stop (LPCTSTR newText, BOOL resetTxt); ``` -------------------------------- ### Create Object Iterator using CreateAttrIterator Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1434.txt This C code demonstrates how to create an attribute iterator for an object in Kompas. It uses Cursor to select an object, FindObj to locate it, and then CreateAttrIterator to get an iterator. The code also shows how to move the iterator and delete an attribute after prompting for a password. ```c double x, y; reference pObj; char password[11]; int j; RequestInfo info; memset (&info, 0, sizeof(info)); info.prompt = "Укажите объект"; do { j = Cursor (&info, &x ,&y, 0); if (j) { if (ExistObj(pObj = FindObj (x, y, 1e6))) { LightObj (pObj, 1); //создадим итератор для хождения по атрибутам объекта reference iter = CreateAttrIterator (pObj, 0,0,0,0,0); //встали на первый атрибут reference attr = MoveAttrIterator (iter, 'F', 0); if (attr) { j = ReadString ("Ввести пароль типа атрибута", password, 10); if (j) { //удалить атрибут if (!DeleteAttr (pObj, attr, password)) MessageBoxResult();// неудачное завершение " // выдадим результат работы // нашей функции } } else Message("атрибут не найден"); LightObj (pObj, 0); } } } while (j); ``` -------------------------------- ### Create Basic Application Library (Plugin) in C++ Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Shows the basic structure for creating a Windows DLL as a KOMPAS application library. It includes the entry point for commands, library identification functions, and a simple command implementation for creating a bolt. Requires Windows SDK and KOMPAS API typelib. ```cpp // library.cpp - Windows DLL #include #include #import "kAPI7.tlb" // Library entry point extern "C" __declspec(dllexport) void ExternalRunCommand(short command, short mode, IDispatch* kompas) { IApplicationPtr pApp = kompas; switch(command) { case 1: CreateBolt(pApp); break; case 2: CreateGear(pApp); break; case 3: ExportToPDF(pApp); break; } } // Library identification extern "C" __declspec(dllexport) int LIBRARYID() { return 12345; // Unique ID } extern "C" __declspec(dllexport) BSTR LIBRARYNAME() { return SysAllocString(L"MechanicalLibrary"); } extern "C" __declspec(dllexport) BSTR DisplayLibraryName() { return SysAllocString(L"Mechanical Components"); } // Command implementation void CreateBolt(IApplicationPtr pApp) { IDocumentsPtr pDocs = pApp->Documents; IKompasDocumentPtr pDoc = pDocs->Add(ksDocumentPart, VARIANT_TRUE); // Create bolt geometry... } ``` -------------------------------- ### Create New KOMPAS Document (C++) Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Creates a new 3D part document in KOMPAS-3D using COM automation and saves it to a specified path. Requires the 'kAPI7.tlb' type library. ```cpp #include #import "kAPI7.tlb" int main() { CoInitialize(NULL); IApplicationPtr pKompas; pKompas.CreateInstance("Kompas.Application.7"); pKompas->Visible = VARIANT_TRUE; IDocumentsPtr pDocs = pKompas->Documents; // Create 3D part document IKompasDocumentPtr pDoc = pDocs->Add(ksDocumentPart, VARIANT_TRUE); IKompasDocument3DPtr pDoc3D = pDoc; // Save document pDoc->SaveAs("C:\\output\\part.m3d"); CoUninitialize(); return 0; } ``` -------------------------------- ### Create Assembly with Parts using C++ Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Constructs a new assembly document and inserts component parts. The first component can be fixed in place, while subsequent components can be added and constrained. Component files are specified by their paths. ```cpp // Create assembly document IKompasDocumentPtr pAsmDoc = pDocs->Add(ksDocumentAssembly, VARIANT_TRUE); IKompasDocument3DPtr pAsm3D = pAsmDoc; IPart7Ptr pAsmPart = pAsm3D->RootPart; // Insert first component IEntity7Ptr pPartDef1 = pAsmPart->NewEntity(o3d_component); IComponentDefinitionPtr pCompDef1 = pPartDef1->GetDefinition(); pCompDef1->FileName = "C:\\parts\\base.m3d"; pCompDef1->SetFixed(VARIANT_TRUE); // Fix first part IFeature7Ptr pComponent1 = pPartDef1->Create(); // Insert second component IEntity7Ptr pPartDef2 = pAsmPart->NewEntity(o3d_component); IComponentDefinitionPtr pCompDef2 = pPartDef2->GetDefinition(); pCompDef2->FileName = "C:\\parts\\bracket.m3d"; IFeature7Ptr pComponent2 = pPartDef2->Create(); ``` -------------------------------- ### Get Library Attribute Types Array using ksGetLibraryAttrTypesArray Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1434.txt This C code example shows how to retrieve an array of attribute types from a Kompas library file (e.g., spc.lat). It uses ksGetLibraryAttrTypesArray to get the array, GetArrayCount to determine the number of types, and GetArrayItem to access details of each type, such as ID and name. ```c //получим массив типов атрибутов в spc.lat reference typeArr = ksGetLibraryAttrTypesArray(("d:\\0\\Spc.lat")); // полное имя библиотеки //стилей if (typeArr) { char buf[128]; //определим количество типов и отобразим на экране int count = GetArrayCount(typeArr); sprintf(buf, "count = %d", count); Message(buf); //в цикле получим информацию о каждом типе и отобразим на экране for (uint i = 0; i < count; i) { LibraryAttrTypeParam par; GetArrayItem(typeArr, // указатель на массив i, // индекс в массиве (нумерация начинается с 0) &par, // указатель на структуру элемента sizeof(LibraryAttrTypeParam)); // размер структуры элемента sprintf(buf, "ID = %f\nname=%s", par.typeId, par.name); Message(buf); } } ``` -------------------------------- ### Create Drawing View with Projections (C++) Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Demonstrates how to create projection views in a KOMPAS drawing document using C++ COM automation. It sets the properties of a base view and then creates a new projection view based on it. ```cpp IDrawingDocumentPtr pDrawDoc = pDoc; IViewsPtr pViews = pDrawDoc->Views; // Get base view IViewPtr pBaseView = pViews->Item(0); pBaseView->X = 100; pBaseView->Y = 100; pBaseView->Scale = 1.0; // Create projection view IViewPtr pProjection = pViews->Add(); pProjection->BaseView = pBaseView; pProjection->ProjectionType = vpTop; pProjection->X = 100; pProjection->Y = 200; ``` -------------------------------- ### Document Management API Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt APIs for managing KOMPAS-3D documents, including creating new ones, opening existing files, and processing documents in batch mode. ```APIDOC ## Create New Document ### Description Creates new documents in KOMPAS using COM automation, supporting various document types like drawings, parts, and assemblies. ### Method COM Automation (e.g., C++ with `Add` method) ### Endpoint N/A (COM Interface) ### Parameters #### COM Object Methods - **ksDocumentPart** (enum) - Type of document to create (e.g., part). - **VARIANT_TRUE** (VARIANT_BOOL) - Parameter to indicate if the document should be visible. ### Request Example ```cpp #include #import "kAPI7.tlb" int main() { CoInitialize(NULL); IApplicationPtr pKompas; pKompas.CreateInstance("Kompas.Application.7"); pKompas->Visible = VARIANT_TRUE; IDocumentsPtr pDocs = pKompas->Documents; IKompasDocumentPtr pDoc = pDocs->Add(ksDocumentPart, VARIANT_TRUE); pDoc->SaveAs("C:\\output\\part.m3d"); CoUninitialize(); return 0; } ``` ### Response #### Success Response - **IKompasDocumentPtr** - Pointer to the newly created KOMPAS document object. #### Response Example (Refer to Request Example for code structure leading to document creation.) ## Open Existing Document ### Description Opens existing KOMPAS documents and provides methods for manipulation and saving, including error handling. ### Method Export Functions (e.g., C/C++) ### Endpoint N/A (Function Calls) ### Parameters #### Function Parameters - **"C:\drawings\part.cdw"** (string) - Path to the document file. - **0** (integer) - Mode or flag for opening the document. ### Request Example ```cpp // Using export functions #include "LDefin2D.h" reference doc = OpenDocument("C:\\drawings\\part.cdw", 0); if (doc != 0) { // Document opened successfully if (IsDocumentChanged(doc)) { SaveDocument(doc); } CloseDocument(doc); } ``` ### Response #### Success Response - **reference** - A reference handle to the opened document if successful, otherwise 0. #### Response Example (Refer to Request Example for code structure.) ## Batch Document Processing ### Description Allows for invisible processing of multiple documents, suitable for automated operations and background tasks. ### Method COM Automation (e.g., Python with `win32com`) ### Endpoint N/A (COM Interface and Function Calls) ### Parameters #### COM Object Methods & Function Parameters - **"Kompas.Application.7"** (string) - COM server name. - **False** (boolean) - `Visible` property set to `False` for invisible mode. - **file_list** (list of strings) - List of filenames to process. - **"C:\\parts\\{filename}"** (string) - Path to the document file to open. - **0** (integer) - Parameter for closing the document (e.g., without saving changes). ### Request Example ```python import win32com.client kompas = win32com.client.Dispatch("Kompas.Application.7") kompas.Visible = False # Invisible mode for batch processing docs = kompas.Documents file_list = ["part1.m3d", "part2.m3d", "part3.m3d"] for filename in file_list: doc = docs.Open(f"C:\\parts\\{filename}", False) # Perform operations part = doc.RootPart # ... modify part ... doc.SaveAs(f"C:\\export\\{filename}.stp") doc.Close(0) # Close without saving original ``` ### Response #### Success Response - **None** (Implicit success if no errors are raised during processing). #### Response Example (Refer to Request Example for code structure.) ``` -------------------------------- ### Set and Get Document Type using KGAX1.DocumentType and KGAX1.SetDocumentType Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1434.txt This C code snippet shows how to set and get the document type of an object, presumably a Kompas document object represented by KGAX1. It uses direct assignment for the type (KGAX1.DocumentType) and specific setter/getter methods (KGAX1.SetDocumentType and KGAX1.GetDocumentType). ```c KGAX1.DocumentType = vt_SheetStandart; (* ) Type = KGAX1.DocumentType; (* ) KGAX1.SetText (vt_SheetStandart); (**) Type = KGAX1.GetDocumentType(); (**) ``` -------------------------------- ### Configure Roughness Parameters in Kompas API Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1398.txt Initializes and sets parameters for roughness representation in Kompas. This includes setting the roughness type, orientation, reference point, angle, and the number of text lines. ```c void Rough_Example (void) { reference p; RoughParam roughPar; memset (&roughPar, 0, sizeof (RoughParam)); //заполним параметры шероховатости roughPar.rPar.type=0;// без обработки roughPar.rPar.around=0; roughPar.rPar.x = 50; roughPar.rPar.y = 50;// опорная точка roughPar.rPar.ang = 90;// угол наклона оси знака roughPar.rPar.cText0=1;// строк над знаком ``` -------------------------------- ### 2D Drawing API Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt APIs for creating and manipulating 2D geometric entities, annotations, and drawing views within KOMPAS-3D. ```APIDOC ## Draw Basic Geometry ### Description Creates fundamental 2D geometric entities such as lines, circles, and arcs. ### Method Export Functions (e.g., C/C++) ### Endpoint N/A (Function Calls) ### Parameters #### Function Parameters - **lt_DocSheetStandart** (enum) - Type of document sheet. - **ksLineSeg(0, 0, 100, 100, 1)** (function call) - Creates a line segment from (0,0) to (100,100) with a specified style. - **ksCircle(50, 50, 25, 1)** (function call) - Creates a circle centered at (50,50) with radius 25 and a specified style. - **ksArcByPoint(0, 0, 40, 40, 0, 0, 40, 1, 1)** (function call) - Creates an arc using points and radii. ### Request Example ```cpp // Using export functions reference doc = CreateDocument(lt_DocSheetStandart, NULL, 0); // Draw line reference line = ksLineSeg(0, 0, 100, 100, 1); // Draw circle reference circle = ksCircle(50, 50, 25, 1); // Draw arc (center at 0,0, radius 40, from point 40,0 to 0,40, counterclockwise) reference arc = ksArcByPoint(0, 0, 40, 40, 0, 0, 40, 1, 1); // Update view ksReDrawDocument(); ``` ### Response #### Success Response - **reference** - Handles to the created geometric entities. #### Response Example (Refer to Request Example for code structure.) ## Create Complex Contour with Polyline ### Description Builds closed contours using polylines, which can be used for subsequent operations like hatching or creating extrusion bases. ### Method Export Functions (e.g., C/C++) ### Endpoint N/A (Function Calls) ### Parameters #### Function Parameters - **ksPolyline(1)** (function call) - Initializes a polyline object. - **ksPointByParam(x, y, bulge, point_type)** (function call) - Adds a point to the polyline, where `bulge` defines an arc segment. - **ksEndObj()** (function call) - Finalizes the polyline object. ### Request Example ```cpp // Create polyline (closed contour) reference polyline = ksPolyline(1); // Add points (x, y, bulge, point_type) ksPointByParam(0, 0, 0, 0); ksPointByParam(100, 0, 0, 0); ksPointByParam(100, 50, 0.5, 0); // 0.5 bulge creates arc ksPointByParam(50, 100, 0, 0); ksPointByParam(0, 50, 0, 0); // Close polyline ksEndObj(); ``` ### Response #### Success Response - **reference** - Handle to the created polyline object. #### Response Example (Refer to Request Example for code structure.) ## Add Text and Dimensions ### Description Annotates drawings by adding text labels and dimensional constraints. ### Method COM Automation (e.g., Visual Basic) ### Endpoint N/A (COM Interface) ### Parameters #### COM Object Properties & Methods - **ksMText** (object) - Structure for defining MText properties (position, text content, height, angle). - **ksDimension** (object) - Structure for defining dimension properties (position, type). - **dt_LinearDimension** (enum) - Type of dimension (linear). ### Request Example ```vb ' Visual Basic Example Dim kompas As KompasObject Dim doc As ksDocument2D Dim textObj As Long Set kompas = GetObject(, "Kompas.Application.5") Set doc = kompas.Document2D() ' Add text Dim textParam As ksMText Set textParam = kompas.GetParamStruct(ko_MText) textParam.x = 50 textParam.y = 50 textParam.angle = 0 textParam.text = "SAMPLE TEXT" textParam.height = 5 textObj = doc.ksMText(textParam, 0) ' Add linear dimension Dim dimParam As ksDimension Set dimParam = kompas.GetParamStruct(ko_Dimension) dimParam.x = 50 dimParam.y = -20 dimParam.dimType = dt_LinearDimension doc.ksDimension(dimParam) ``` ### Response #### Success Response - **Long** - Identifiers for the created text and dimension objects. #### Response Example (Refer to Request Example for code structure.) ## Create Drawing View with Projections ### Description Sets up multiple views in a drawing document, including base views and projected views with automatic alignment. ### Method COM Automation (e.g., C++ with `IDrawingDocumentPtr`) ### Endpoint N/A (COM Interface) ### Parameters #### COM Object Properties & Methods - **IViewsPtr** - Interface for managing views within a document. - **IViewPtr** - Interface representing a single view. - **vpTop** (enum) - Specifies the projection type (e.g., top view). - **X, Y** (double) - Coordinates for view placement. - **Scale** (double) - Scaling factor for the view. - **BaseView** (IViewPtr) - Reference to the view upon which the projection is based. - **ProjectionType** (vpType) - The type of projection. ### Request Example ```cpp IDrawingDocumentPtr pDrawDoc = pDoc; IViewsPtr pViews = pDrawDoc->Views; // Get base view IViewPtr pBaseView = pViews->Item(0); pBaseView->X = 100; pBaseView->Y = 100; pBaseView->Scale = 1.0; // Create projection view IViewPtr pProjection = pViews->Add(); pProjection->BaseView = pBaseView; pProjection->ProjectionType = vpTop; pProjection->X = 100; pProjection->Y = 200; ``` ### Response #### Success Response - **IViewPtr** - Pointers to the created view objects (base view and projection view). #### Response Example (Refer to Request Example for code structure.) ``` -------------------------------- ### Add Assembly Constraints (Mates) in C++ Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Demonstrates how to add coincident and distance constraints between component faces in KOMPAS using C++. It involves creating mate definitions, selecting faces, setting parameters, and creating the mate features. Requires KOMPAS API typelib. ```cpp // Add coincident constraint IEntity7Ptr pMateDef = pAsmPart->NewEntity(o3d_coincidence); ICoincidenceDefinitionPtr pMateParams = pMateDef->GetDefinition(); // Select face from component 1 IFacePtr pFace1 = pComponent1->GetFace(0); // Select face from component 2 IFacePtr pFace2 = pComponent2->GetFace(5); pMateParams->SetEntity(0, pFace1); pMateParams->SetEntity(1, pFace2); IFeature7Ptr pMate = pMateDef->Create(); // Add distance constraint IEntity7Ptr pDistDef = pAsmPart->NewEntity(o3d_distance); IDistanceDefinitionPtr pDistParams = pDistDef->GetDefinition(); pDistParams->SetEntity(0, pFace3); pDistParams->SetEntity(1, pFace4); pDistParams->Distance = 25.0; // 25mm gap IFeature7Ptr pDistMate = pDistDef->Create(); ``` -------------------------------- ### Define Library Toolbar in C++ Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Explains how to define custom toolbar buttons for a KOMPAS application library. It includes functions to specify toolbar IDs and button IDs, linking them to library commands. Requires KOMPAS API typelib and resource file for icons. ```cpp // Define toolbar buttons extern "C" __declspec(dllexport) int LibToolBarId(int barType, int index) { // barType: 0=compact panel, 1=toolbar, 2=context panel // index: toolbar row (0=top, 1=bottom) if (barType == 1 && index == 0) { return 100; // Toolbar ID } return 0; } extern "C" __declspec(dllexport) int LibToolBarBtnId(int toolBarId, int btnIndex) { if (toolBarId == 100) { switch(btnIndex) { case 0: return 1; // Command 1 button case 1: return 2; // Command 2 button case 2: return 3; // Command 3 button default: return 0; } } return 0; } // Button icon resource IDs (in .rc file) // IDB_BTN1 = 1001 // IDB_BTN2 = 1002 // IDB_BTN3 = 1003 ``` -------------------------------- ### Import DXF/DWG Files into KOMPAS (C++) Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Loads AutoCAD DXF and DWG files into KOMPAS. This C++ code shows how to configure import parameters, such as importing as a fragment for DXF or preserving layer structure for DWG, before opening the files. ```cpp IDocumentsPtr pDocs = pApp->Documents; // Import DXF IDXFImportParamPtr pDxfParams = pApp->DXFImportParam; pDxfParams->Init(); pDxfParams->ImportAsFragment = VARIANT_TRUE; // Import as fragment pDxfParams->ScaleFactor = 1.0; IKompasDocumentPtr pDoc = pDocs->OpenWithParam( "C:\\import\\drawing.dxf", VARIANT_TRUE, // Visible pDxfParams ); // Import DWG (requires converter library) IDWGImportParamPtr pDwgParams = pApp->DWGImportParam; pDwgParams->Init(); pDwgParams->PreserveLayerStructure = VARIANT_TRUE; IKompasDocumentPtr pDoc2 = pDocs->OpenWithParam( "C:\\import\\drawing.dwg", VARIANT_TRUE, pDwgParams ); ``` -------------------------------- ### Draw Ellipse Arc - Kompas API Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1388.txt Generates an elliptical arc using the `KsEllipseArc` function. It requires an `EllipseArcParam` structure containing the center coordinates (xc, yc), semi-axes (a, b), ellipse tilt angle (ang), arc start and end angles (angFirst, angSecond), direction (dir), and line style (style). ```c++ EllipseArcParam par; memset(&info, 0, sizeof(info)); par.xc = 20; par.yc = 20; //координаты центра par.a = 30; par.b = 10; //полуоси эллипса par.ang = 45; //угол наклона эллипса к оси X par.angFirst = 10; //начальный угол дуги par.angSecond =300; //конечный угол дуги par.dir = 1; //направление par.style = 1; //тип линии reference p = KsEllipseArc(&par); ``` -------------------------------- ### Batch Process KOMPAS Documents (Python) Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Automates the processing of multiple KOMPAS documents in invisible mode using Python and `win32com.client`. It opens, modifies (placeholder), saves as STEP, and closes each document. ```python import win32com.client kompas = win32com.client.Dispatch("Kompas.Application.7") kompas.Visible = False # Invisible mode for batch processing docs = kompas.Documents file_list = ["part1.m3d", "part2.m3d", "part3.m3d"] for filename in file_list: doc = docs.Open(f"C:\\parts\\{filename}", False) # Perform operations part = doc.RootPart # ... modify part ... # Export to STEP doc.SaveAs(f"C:\\export\\{filename}.stp") doc.Close(0) # Close without saving original ``` -------------------------------- ### Draw Basic 2D Geometry (C++) Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Demonstrates drawing basic 2D geometric entities like lines, circles, and arcs in a KOMPAS drawing using export functions. Updates the document view after drawing. ```cpp // Using export functions reference doc = CreateDocument(lt_DocSheetStandart, NULL, 0); // Draw line reference line = ksLineSeg(0, 0, 100, 100, 1); // Draw circle reference circle = ksCircle(50, 50, 25, 1); // Draw arc (center at 0,0, radius 40, from point 40,0 to 0,40, counterclockwise) reference arc = ksArcByPoint(0, 0, 40, 40, 0, 0, 40, 1, 1); // Update view ksReDrawDocument(); ``` -------------------------------- ### Bill of Materials (BOM) Access and Export in Python Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Shows how to access component information from a KOMPAS assembly, extract details like name, file path, quantity, mass, and material, and then export this data to a CSV file. This is useful for generating bills of materials. ```python import win32com.client kompas = win32com.client.Dispatch("Kompas.Application.7") doc = kompas.ActiveDocument part = doc.RootPart # Get all components features = part.FeatureCollection(0, 0, 0, 0, 0) bom_data = [] for i in range(features.Count): feature = features.Item(i) if feature.Type == 5: # o3d_component comp_def = feature.GetDefinition() item = { 'name': feature.Name, 'file': comp_def.FileName, 'quantity': 1, 'mass': feature.Mass, 'material': feature.Material } bom_data.append(item) # Export to CSV import csv with open('bom.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=['name', 'file', 'quantity', 'mass', 'material']) writer.writeheader() writer.writerows(bom_data) ``` -------------------------------- ### Subscribe to KOMPAS Document Events (C++) Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Handles document lifecycle events like activation, saving, and closing. This C++ code defines a handler class that implements the IKompasDocumentNotify interface and demonstrates how to connect and disconnect it to the KOMPAS application. ```cpp #include #include class CDocumentEventHandler : public IDispatchImpl { public: // Document activated STDMETHOD(Activate)() { MessageBox(NULL, "Document activated", "Event", MB_OK); return S_OK; } // Before save STDMETHOD(BeginSave)() { // Validate document before save // Return S_FALSE to cancel save return S_OK; } // After save STDMETHOD(EndSave)() { // Log save operation return S_OK; } // Before close STDMETHOD(BeginClose)() { // Cleanup resources return S_OK; } }; // Connect event handler IKompasDocument2D1Ptr pDoc2D = pDoc; IConnectionPointContainerPtr pCPC = pDoc2D; IConnectionPointPtr pCP; pCPC->FindConnectionPoint(__uuidof(IKompasDocumentNotify), &pCP); CDocumentEventHandler* pHandler = new CDocumentEventHandler(); DWORD cookie; pCP->Advise(pHandler, &cookie); // Later: disconnect // pCP->Unadvise(cookie); ``` -------------------------------- ### ksRectangle Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1388.txt Creates a rectangle. ```APIDOC ## POST /ksRectangle ### Description Creates a rectangle with specified dimensions and properties. ### Method POST ### Endpoint /ksRectangle ### Parameters #### Request Body - **x** (number) - X coordinate of the base point - **y** (number) - Y coordinate of the base point - **ang** (number) - Angle of the vector from the first to the second point - **height** (number) - Height of the rectangle - **weight** (number) - Width of the rectangle - **pCorner** (array) - Array of corner parameters - **style** (number) - Line style ### Request Example ```json { "x": "73.55", "y": 39.95, "ang": 0.00, "height": "66.68", "weight": 79.90, "pCorner": [], "style": 1 } ``` ### Response #### Success Response (200) - **reference** (object) - A reference to the created rectangle. #### Response Example ```json { "reference": "" } ``` ``` -------------------------------- ### Export KOMPAS 3D Models to STEP and IGES (C++) Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Converts KOMPAS 3D models to neutral CAD formats STEP (AP214) and IGES (v5.3). This C++ code snippet demonstrates setting export parameters like version and precision, and performing the save operations. ```cpp IKompasDocument3DPtr pDoc3D = pDoc; // Export to STEP IStepExportParamPtr pStepParams = pDoc3D->StepExportParam; pStepParams->Init(); pStepParams->StepVersion = sv_AP214; pStepParams->Precision = 0.01; // 0.01mm tolerance VARIANT_BOOL result = pDoc3D->SaveAsToSTEP("C:\\export\\model.stp", pStepParams); // Export to IGES IIgesExportParamPtr pIgesParams = pDoc3D->IgesExportParam; pIgesParams->Init(); pIgesParams->Version = iv_5_3; pIgesParams->Precision = 0.01; result = pDoc3D->SaveAsToIGES("C:\\export\\model.igs", pIgesParams); if (!result) { IErrorPtr pError = pDoc3D->LastError; // Handle export error } ``` -------------------------------- ### ksEllipse Source: https://github.com/dwnmf/-kompas-api-docv3/blob/main/part_1388.txt Creates an ellipse. ```APIDOC ## POST /ksEllipse ### Description Creates an ellipse based on center coordinates, semi-axes, and rotation angle. ### Method POST ### Endpoint /ksEllipse ### Parameters #### Request Body - **xc** (number) - X coordinate of the ellipse center - **yc** (number) - Y coordinate of the ellipse center - **a** (number) - Semi-major axis length - **b** (number) - Semi-minor axis length - **ang** (number) - Ellipse rotation angle in degrees - **style** (number) - Line style ### Request Example ```json { "xc": 20, "yc": 20, "a": 30, "b": 10, "ang": 45, "style": 1 } ``` ### Response #### Success Response (200) - **reference** (object) - A reference to the created ellipse. #### Response Example ```json { "reference": "" } ``` ``` -------------------------------- ### Open and Process KOMPAS Document (Export Functions) Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Opens an existing KOMPAS document using export functions, checks if it has been modified, saves if necessary, and then closes the document. It handles basic document operations. ```cpp // Using export functions #include "LDefin2D.h" reference doc = OpenDocument("C:\\drawings\\part.cdw", 0); if (doc != 0) { // Document opened successfully // Check if modified if (IsDocumentChanged(doc)) { SaveDocument(doc); } CloseDocument(doc); } ``` -------------------------------- ### Custom Property Manager Panel in C++ Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Explains how to create custom interactive property panels within the KOMPAS user interface. This involves adding various control types like spin edits, list boxes, and checkboxes to a property manager and retrieving their values later. ```cpp IPart7Ptr pPart = pDoc3D->RootPart; IPropertyManagerPtr pPropMgr = pPart->PropertyManager; // Start editing pPropMgr->StartEdit(); IPropertyControlsPtr pControls = pPropMgr->PropertyControls; // Add numeric spin control IPropertySpinEditPtr pLength = pControls->Add(ksControlSpinReal); pLength->Name = "Length"; pLength->Value = 100.0; pLength->SetValueRange(10.0, 1000.0); pLength->Step = 5.0; // Add list box IPropertyListPtr pMaterial = pControls->Add(ksControlList); pMaterial->Name = "Material"; pMaterial->AddItem("Steel"); pMaterial->AddItem("Aluminum"); pMaterial->AddItem("Brass"); pMaterial->SelectedItemIndex = 0; // Add checkbox IPropertyCheckBoxPtr pThreaded = pControls->Add(ksControlCheckBox); pThreaded->Name = "Add threads"; pThreaded->Value = VARIANT_TRUE; // Show panel pPropMgr->EndEdit(); // Later: get values double lengthValue = pLength->Value; int materialIndex = pMaterial->SelectedItemIndex; bool isThreaded = (pThreaded->Value == VARIANT_TRUE); ``` -------------------------------- ### Parametric Design with Variables in C++ Source: https://context7.com/dwnmf/-kompas-api-docv3/llms.txt Demonstrates how to create and manipulate variables within a KOMPAS part to drive parametric design. Variables can be used for dimensions, expressions, and feature parameters. Changes to variables trigger automatic model recalculations. ```cpp IPart7Ptr pPart = pDoc3D->RootPart; // Create variables IVariablesCollectionPtr pVars = pPart->Variables; IVariablePtr pWidth = pVars->Add(); pWidth->Name = "Width"; pWidth->Value = 100.0; pWidth->Description = "Overall width"; IVariablePtr pHeight = pVars->Add(); pHeight->Name = "Height"; pHeight->Value = 50.0; // Use in expressions IVariablePtr pArea = pVars->Add(); pArea->Name = "Area"; pArea->Expression = "Width * Height"; // Computed variable // Reference in features IBossExtrusionDefinitionPtr pExtParams = pExtDef->GetDefinition(); pExtParams->Depth1 = pHeight->Value; // Later: modify parameters pWidth->Value = 150.0; pPart->RebuildDocument(); // Recalculate model ```