Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Theme
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Create API Key
Add Docs
Kompas API
https://github.com/dwnmf/kompas-api-doc
Admin
Kompas API offers programmatic access to functionalities and data of the Kompas platform or service.
Tokens:
18,867
Snippets:
53
Trust Score:
4.1
Update:
6 months ago
Context
Skills
Chat
Benchmark
1.7
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# KOMPAS-Invisible API Documentation KOMPAS-Invisible is the official API for KOMPAS-3D, a professional CAD system developed by ASCON. This API provides comprehensive programmatic access to both 2D drafting and 3D solid modeling capabilities. The system is built on COM/ActiveX technology, offering dual implementation paths: high-performance export functions via DLL modules and flexible Automation interfaces. KOMPAS-Invisible enables developers to create custom libraries, automate design workflows, integrate external systems, and extend KOMPAS-3D functionality across multiple programming languages. The API architecture separates 2D and 3D capabilities into distinct modules while maintaining a unified object model. The 2D API handles graphical documents including drawings and fragments, supporting geometric primitives, dimensions, annotations, and macroelements. The 3D API provides access to parametric solid modeling operations including extrusions, revolutions, lofts, Boolean operations, and feature-based modeling. Both APIs support event-driven programming, custom library development, and seamless integration with KOMPAS-3D's native functionality through well-defined COM interfaces. ## API Reference ### Getting Active Document and Accessing Interfaces Access the currently active KOMPAS document and query for specific interfaces using COM's QueryInterface mechanism. ```cpp // C++ with smart pointers #include "KompasAPI7.h" IApplicationPtr kompasApp; HRESULT hr = kompasApp.CreateInstance(L"Kompas.Application.7"); if (SUCCEEDED(hr)) { IKompasDocumentPtr kompasDoc = kompasApp->GetActiveDocument(); IDrawingDocumentPtr doc2D = kompasDoc; // QueryInterface happens automatically if (doc2D != NULL) { // Work with 2D drawing doc2D->RebuildDocument(); } } // C# example using Kompas6API7; IApplication kompasApp = (IApplication)Activator.CreateInstance( Type.GetTypeFromProgID("Kompas.Application.7")); IKompasDocument kompasDoc = kompasApp.ActiveDocument; IDrawingDocument doc2D = (IDrawingDocument)kompasDoc; // Cast performs QueryInterface // Python example import win32com.client import pythoncom kompasApp = win32com.client.Dispatch("Kompas.Application.7") kompasDoc = kompasApp.ActiveDocument doc2D = kompasDoc._oleobj_.QueryInterface( pythoncom.IID_IDispatch) ``` ### Creating a Simple KOMPAS Library (DLL Export Functions) Build a basic library that draws geometric objects using export functions. This is the fastest method for library creation. ```cpp // SimpleLibrary.cpp #include "libtool.h" #include <windows.h> // Required: Library name displayed in KOMPAS extern "C" char* WINAPI LIBRARYNAME() { return "My Drawing Library"; } // Required: Library unique identifier extern "C" unsigned int WINAPI LIBRARYID() { return 1000; // Unique ID } // Required: Entry point called when library command is executed extern "C" void WINAPI LIBRARYENTRY(unsigned int comm) { switch (comm) { case 1: // Command 1: Draw rectangle Message("Drawing rectangle..."); // Draw using global coordinates (mm) LineSeg(0, 0, 100, 0, 1); // Bottom LineSeg(100, 0, 100, 50, 1); // Right LineSeg(100, 50, 0, 50, 1); // Top LineSeg(0, 50, 0, 0, 1); // Left break; case 2: // Command 2: Draw circle Message("Drawing circle..."); Circle(50, 25, 20, 1); // x, y, radius, line_type break; } } // Optional: Command state (enable/disable/check) extern "C" int WINAPI LibCommandState(unsigned int comm, int* enable, int* check) { *enable = 1; // Enable command *check = 0; // Unchecked return 1; } // DEF file (SimpleLibrary.def): // EXPORTS // LIBRARYID @1 // LIBRARYENTRY @2 // LIBRARYNAME @3 // LibCommandState @4 ``` ### Interactive Input with Cursor and Dynamic Preview Create interactive drawing commands with real-time preview using callback functions. ```cpp // Cursor with phantom callback #include "libtool.h" struct PhantomData { int type; double baseX, baseY; double radius; reference group; }; // Callback function for dynamic preview int __export __pascal CallBackFunc(int command, double* x, double* y, RequestInfo* info, void* phantom, int dynamic) { PhantomData* data = (PhantomData*)phantom; switch (command) { case -1: // Place object in model if (data->group) { MoveObj(data->group, *x, *y); StoreTmpGroup(data->group); ClearGroup(data->group); data->group = 0; } return 1; case 0: // Update phantom preview if (data->group) DeleteObj(data->group); // Create temporary preview group data->group = NewGroup(1); // 1 = temporary Circle(0, 0, data->radius, 1); Text("Circle", 0, data->radius + 5, 0, 3.5, 0); EndGroup(); return 1; case 1: // User selected "Square" from context menu data->radius = 30; return 1; case 2: // User selected "Triangle" from context menu data->radius = 40; return 1; } return 1; } void InteractiveCirclePlacement() { PhantomData phantomData = {0}; phantomData.radius = 25.0; // Create initial phantom phantomData.group = NewGroup(1); Circle(0, 0, phantomData.radius, 1); EndGroup(); // Setup request info RequestInfo info; memset(&info, 0, sizeof(info)); info.prompt = "Click to place circle"; info.commands = "!Square !Triangle"; // Context menu items info.callBack = CallBackFunc; double x, y; int result = Cursor(&info, &x, &y, &phantomData); if (result > 0) { // User placed object successfully Message("Circle placed!"); } } ``` ### Working with 2D Views and Parameters Access and modify view properties in 2D drawings using parameter structures. ```cpp #include "KompasAPI7.h" // Structure for view parameters (Unicode version) struct ViewParamW { unsigned short state; // View state flags double x, y; // Attachment point coordinates double scale; // View scale factor double ang; // Rotation angle in radians unsigned long color; // RGB color wchar_t name[128]; // View name }; void ModifyViewProperties() { // Get active 2D document IKompasDocument2D1Ptr doc2D = GetActiveDocument2D(); if (doc2D) { // Get view collection IViewsPtr views = doc2D->GetViews(); long count = views->GetCount(); for (long i = 0; i < count; i++) { IViewPtr view = views->GetView(i); ViewParamW params; // Get current parameters view->GetObjParam(¶ms, sizeof(params)); // Modify view params.scale = 2.0; // Double scale params.ang = 0.785398; // 45 degrees params.color = RGB(255, 0, 0); // Red wcscpy_s(params.name, L"Modified View"); // Apply changes view->SetObjParam(¶ms, sizeof(params)); view->Update(); } doc2D->RebuildDocument(); } } ``` ### Creating 3D Extrusion Feature Build parametric 3D solid features by defining sketch profiles and extrusion parameters. ```cpp #include "KompasAPI7.h" void Create3DExtrusion() { // Get active 3D part document IPartDocumentPtr partDoc = GetActive3DDocument(); if (partDoc) { IPart7Ptr part = partDoc->GetTopPart(); // Create new sketch on XY plane ISketchsPtr sketches = part->GetSketchs(); ISketchPtr sketch = sketches->Add(); IEntityPtr xyPlane = part->GetDefaultEntity(o3d_planeXOY); sketch->PutPlane(xyPlane); sketch->BeginEdit(); // Get 2D container for sketch IDrawingContainerPtr container = sketch; ILineSegmentsPtr lines = container->GetLineSegments(); // Draw rectangle profile: 100x50mm ILineSegmentPtr line1 = lines->Add(); line1->SetX1(0); line1->SetY1(0); line1->SetX2(100); line1->SetY2(0); ILineSegmentPtr line2 = lines->Add(); line2->SetX1(100); line2->SetY1(0); line2->SetX2(100); line2->SetY2(50); ILineSegmentPtr line3 = lines->Add(); line3->SetX1(100); line3->SetY1(50); line3->SetX2(0); line3->SetY2(50); ILineSegmentPtr line4 = lines->Add(); line4->SetX1(0); line4->SetY1(50); line4->SetX2(0); line4->SetY2(0); sketch->EndEdit(); sketch->Update(); // Create extrusion operation IExtrusionsPtr extrusions = part->GetExtrusions(); IExtrusionPtr extrusion = extrusions->Add(ksObj3dTypeEnum::o3d_baseExtrusion); extrusion->PutSketch(sketch); extrusion->PutDirection(ksDirectionTypeEnum::dtNormal); // Normal to sketch extrusion->PutDepth(25.0); // Extrude 25mm // Execute feature if (extrusion->Update()) { partDoc->RebuildDocument(); MessageBox(NULL, L"Extrusion created successfully!", L"Success", MB_OK); } else { MessageBox(NULL, L"Failed to create extrusion", L"Error", MB_OK | MB_ICONERROR); } } } ``` ### Creating Specification Objects with Geometry Links Generate specification table entries linked to drawing geometry for automated BOM creation. ```cpp #include "ltcom5.h" #define SPC_NAME 5 // Name column #define SPC_MARK 1 // Designation/Mark column #define SPC_QUANTITY 4 // Quantity column reference CreateSpecificationObject(reference geometryRef) { reference spcObj = 0; // Check if editing existing macro if (::EditMacroMode()) { // Find specification object by geometry spcObj = ::ksGetSpcObjForGeom("graphic.lyt", 1, 0, 1, 1); if (spcObj && !::ksSpcObjectEdit(spcObj)) { spcObj = 0; } } // Create new specification object if (!spcObj) { // Layout "graphic.lyt", section 1, base object type 20 if (!::ksSpcObjectCreate("graphic.lyt", 1, 20, 0, 0, 0)) { return 0; } } // Set specification values ::ksSpcChangeValue(SPC_NAME, 1, "Втулка", STRING_ATTR_TYPE); ::ksSpcChangeValue(SPC_MARK, 1, "ДСП.001.015", STRING_ATTR_TYPE); ::ksSpcChangeValue(SPC_QUANTITY, 1, "2", STRING_ATTR_TYPE); // Attach drawing geometry to spec object if (geometryRef) { if (!::ksSpcIncludeReference(geometryRef, 1)) { ::ksSpcObjectCancel(); return 0; } } // Finalize spec object spcObj = ::ksSpcObjectEnd(); if (spcObj) { // Open edit window for user review if (::ksEditWindowSpcObject(spcObj)) { return spcObj; } } return 0; } // Example usage void CreatePartWithSpecification() { // Create geometry reference rectGroup = NewGroup(0); // 0 = permanent group LineSeg(0, 0, 50, 0, 1); LineSeg(50, 0, 50, 30, 1); LineSeg(50, 30, 0, 30, 1); LineSeg(0, 30, 0, 0, 1); reference geomRef = EndGroup(); // Create linked specification object reference spcRef = CreateSpecificationObject(geomRef); if (spcRef) { Message("Specification object created successfully"); } } ``` ### Registering AddIn Library for Auto-Load Create a self-registering library that loads automatically when KOMPAS starts. ```cpp #include <windows.h> #include <shlwapi.h> #pragma comment(lib, "shlwapi.lib") extern "C" char* WINAPI LIBRARYNAME() { return "AutoLoad AddIn Library"; } extern "C" void WINAPI LIBRARYENTRY(unsigned int comm) { // AddIn initialization code MessageBox(NULL, L"AddIn library loaded!", L"Info", MB_OK); } // DLL registration function extern "C" HRESULT WINAPI DllRegisterServer() { HKEY hKey; TCHAR szPath[MAX_PATH]; DWORD dwSize = MAX_PATH; // Get DLL path GetModuleFileName(GetModuleHandle(NULL), szPath, dwSize); // Create registry key LONG result = RegCreateKeyEx( HKEY_CURRENT_USER, L"Software\\ASCON\\KOMPAS-3D\\AddIns\\MyAddIn", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL); if (result != ERROR_SUCCESS) { return E_FAIL; } // Set AutoConnect = 1 (load on startup) DWORD autoConnect = 1; RegSetValueEx(hKey, L"AutoConnect", 0, REG_DWORD, (BYTE*)&autoConnect, sizeof(DWORD)); // Set DLL path RegSetValueEx(hKey, L"Path", 0, REG_SZ, (BYTE*)szPath, (lstrlen(szPath) + 1) * sizeof(TCHAR)); RegCloseKey(hKey); return S_OK; } // DLL unregistration function extern "C" HRESULT WINAPI DllUnregisterServer() { LONG result = RegDeleteKey( HKEY_CURRENT_USER, L"Software\\ASCON\\KOMPAS-3D\\AddIns\\MyAddIn"); return (result == ERROR_SUCCESS) ? S_OK : E_FAIL; } // Register library using: regsvr32 MyAddIn.rtw ``` ### Handling Document Events Subscribe to document events for monitoring user actions and responding to changes. ```cpp #include "KompasAPI7.h" // Event handler class class CDocumentEvents : public IDispEventImpl<1, CDocumentEvents, &__uuidof(_IKompasDocumentEvents), &LIBID_KompasAPI7, 1, 0> { public: BEGIN_SINK_MAP(CDocumentEvents) SINK_ENTRY_EX(1, __uuidof(_IKompasDocumentEvents), 1, OnDocumentBeginClose) SINK_ENTRY_EX(1, __uuidof(_IKompasDocumentEvents), 2, OnDocumentClose) SINK_ENTRY_EX(1, __uuidof(_IKompasDocumentEvents), 3, OnDocumentActivate) END_SINK_MAP() // Event handlers HRESULT __stdcall OnDocumentBeginClose(IKompasDocument* doc) { _bstr_t path = doc->GetPathName(); MessageBox(NULL, (wchar_t*)path, L"Document closing", MB_OK); return S_OK; } HRESULT __stdcall OnDocumentClose(long docType) { // Document closed return S_OK; } HRESULT __stdcall OnDocumentActivate(IKompasDocument* doc, VARIANT_BOOL activated) { if (activated) { // Document became active } return S_OK; } }; // Usage void SubscribeToDocumentEvents() { IApplicationPtr kompasApp; kompasApp.CreateInstance(L"Kompas.Application.7"); CDocumentEvents* pEvents = new CDocumentEvents(); IKompasDocumentPtr doc = kompasApp->GetActiveDocument(); // Advise event sink pEvents->DispEventAdvise(doc); // Work with document... // Unadvise when done pEvents->DispEventUnadvise(doc); delete pEvents; } ``` ### Working with Variables in 2D Documents Access and modify document variables for parametric drawings. ```cpp #include "KompasAPI7.h" void ManageDocumentVariables() { IKompasDocument2D1Ptr doc2D = GetActiveDocument2D(); if (doc2D) { IVariableTablePtr varTable = doc2D->GetVariableTable(); // Create new variable IVariable7Ptr newVar = varTable->AddVariable(); newVar->PutName(L"Width"); newVar->PutValue(100.0); newVar->PutComment(L"Component width in mm"); IVariable7Ptr heightVar = varTable->AddVariable(); heightVar->PutName(L"Height"); heightVar->PutExpression(L"Width * 0.618"); // Golden ratio // Access existing variable by name IVariable7Ptr var = doc2D->GetVariable(L"Width"); if (var) { double value = var->GetValue(); _bstr_t expression = var->GetExpression(); // Modify value var->PutValue(150.0); var->Update(); } // Iterate all variables SAFEARRAY* varArray = doc2D->GetVariables(); VARIANT* pVarData; SafeArrayAccessData(varArray, (void**)&pVarData); long lBound, uBound; SafeArrayGetLBound(varArray, 1, &lBound); SafeArrayGetUBound(varArray, 1, &uBound); for (long i = lBound; i <= uBound; i++) { IVariable7Ptr var = pVarData[i].pdispVal; _bstr_t name = var->GetName(); double val = var->GetValue(); // Process variable... } SafeArrayUnaccessData(varArray); doc2D->RebuildDocument(); } } ``` ### Creating Custom Toolbar for Library Define custom toolbars with buttons for library commands. ```cpp // Toolbar icon resource IDs start at base value extern "C" unsigned int WINAPI LibraryBmpBeginID(unsigned int bmpSizeType) { switch (bmpSizeType) { case 0: return 1000; // 16x16 icons start at ID 1000 case 1: return 1100; // 24x24 icons start at ID 1100 case 2: return 1200; // 32x32 icons start at ID 1200 case 3: return 1300; // 48x48 icons start at ID 1300 } return 1000; } // Define toolbar composition extern "C" int WINAPI LibToolBarId(int barType, int index) { // barType: 0 = compact panel, 1 = toolbar, 2 = context panel // index: 0 = first row, 1 = second row switch (barType) { case 0: // Compact panel return 100; // Panel resource ID case 1: // Main toolbar if (index == 0) { // First toolbar - return menu ID with command IDs return 200; // Menu resource with commands 1,2,3... } break; case 2: // Context panel for macro objects if (index == 0) { return 300; // Upper row commands } else if (index == 1) { return 301; // Lower row commands } break; } return 0; // No more toolbars } // Control button states extern "C" int WINAPI LibCommandState(unsigned int comm, int* enable, int* check) { // Check if document is active if (GetActiveDocument() == NULL) { *enable = 0; // Disable command *check = 0; return 1; } *enable = 1; // Enable command // Check state for toggle buttons if (comm == 5) { *check = IsGridEnabled() ? 1 : 0; } else { *check = 0; } return 1; } // Resource file (library.rc) must define: // - Bitmaps: IDB_BITMAP1000, IDB_BITMAP1001, etc. (24-bit color, 192,192,192 = transparent) // - Menus: IDR_MENU200 with MENUITEM commands // - Icon for compact panel: library.ico (12x12, 18x18, 24x24, 36x36) ``` ### Creating C# KOMPAS Library Build a .NET library for KOMPAS using C# with COM interop. ```csharp using System; using System.Runtime.InteropServices; using Kompas6API7; using Microsoft.Win32; namespace MyKompasLibrary { [ComVisible(true)] [Guid("12345678-1234-1234-1234-123456789ABC")] [ClassInterface(ClassInterfaceType.None)] public class KompasLibrary : IKompasLibrary { private IApplication kompasApp; // Library name public string LIBRARYNAME() { return "C# KOMPAS Library"; } // Library ID public uint LIBRARYID() { return 2000; } // Entry point public void LIBRARYENTRY(uint command) { // Get KOMPAS application kompasApp = (IApplication)Marshal.GetActiveObject("Kompas.Application.7"); switch (command) { case 1: DrawRectangle(); break; case 2: CreateExtrusion(); break; } } private void DrawRectangle() { IKompasDocument doc = kompasApp.ActiveDocument; if (doc.DocumentType == DocumentTypeEnum.lt_DocDrawing) { IDrawingDocument drawDoc = (IDrawingDocument)doc; IDrawingContainer container = (IDrawingContainer)drawDoc; ILineSegments lines = container.LineSegments; // Draw 100x50 rectangle ILineSegment l1 = lines.Add(); l1.X1 = 0; l1.Y1 = 0; l1.X2 = 100; l1.Y2 = 0; l1.Update(); ILineSegment l2 = lines.Add(); l2.X1 = 100; l2.Y1 = 0; l2.X2 = 100; l2.Y2 = 50; l2.Update(); ILineSegment l3 = lines.Add(); l3.X1 = 100; l3.Y1 = 50; l3.X2 = 0; l3.Y2 = 50; l3.Update(); ILineSegment l4 = lines.Add(); l4.X1 = 0; l4.Y1 = 50; l4.X2 = 0; l4.Y2 = 0; l4.Update(); drawDoc.RebuildDocument(); } } // COM registration function [ComRegisterFunction] public static void RegisterFunction(Type type) { // Register as KOMPAS library string keyPath = @"CLSID\" + type.GUID.ToString("B") + @"\Kompas_Library"; Registry.ClassesRoot.CreateSubKey(keyPath); // Optional: Register as AddIn for auto-load string addInKey = @"Software\ASCON\KOMPAS-3D\AddIns\" + type.Name; using (RegistryKey key = Registry.CurrentUser.CreateSubKey(addInKey)) { key.SetValue("AutoConnect", 1); key.SetValue("Path", type.Assembly.Location); } } [ComUnregisterFunction] public static void UnregisterFunction(Type type) { string keyPath = @"CLSID\" + type.GUID.ToString("B") + @"\Kompas_Library"; Registry.ClassesRoot.DeleteSubKey(keyPath, false); string addInKey = @"Software\ASCON\KOMPAS-3D\AddIns\" + type.Name; Registry.CurrentUser.DeleteSubKey(addInKey, false); } } } // Project settings required: // 1. Configuration Properties -> Build -> Register for COM Interop = True // 2. Add references to KOMPAS type libraries (use TlbImp.exe to create wrappers) // 3. Register using: RegAsm.exe /codebase MyKompasLibrary.dll ``` ## Summary The KOMPAS-Invisible API provides a powerful and flexible framework for programmatic control of KOMPAS-3D CAD software, supporting both 2D drafting and 3D parametric modeling. Primary use cases include developing custom component libraries for standardized parts (bearings, fasteners, structural elements), automating repetitive design tasks through batch processing, creating industry-specific design tools with custom UI elements, integrating KOMPAS with PLM/ERP systems for data exchange, and generating technical documentation with automated specifications and BOMs. The API excels at parametric design automation where geometric features are driven by variables and expressions, enabling intelligent templates and configurable assemblies. Integration patterns follow standard COM/ActiveX conventions, making the API accessible from virtually any Windows development environment including C++, C#, Python, Delphi, and VBA. Libraries can be deployed as standalone DLL modules loaded on-demand or as AddIn components that integrate seamlessly into KOMPAS menus and toolbars. The dual-path architecture allows developers to choose between high-performance export functions for speed-critical operations and flexible Automation interfaces for rapid prototyping and scripting. Event-driven programming enables responsive libraries that react to user actions in real-time, while the comprehensive object model provides fine-grained control over every aspect of drawing and modeling operations from low-level geometric primitives to high-level feature-based modeling.