### ksGetObjConstraints, ksDestroyObjConstraint Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Provides a list of constraint types and is a placeholder for examples of getting and destroying object constraints. ```APIDOC ## ksGetObjConstraints, ksDestroyObjConstraint Example ### Description This section lists available constraint types and serves as a placeholder for code examples demonstrating how to retrieve and destroy constraints associated with objects. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c static char *str [] = {"fix point", "point on curve", "horizontal", "vertical", "parallelism of two lines or segments", "perpendicularity of two lines or segments", "equality of lengths of two segments", "equality of radii of two arcs/circles", "align two points horizontally", "align two points vertically", "coincidence of two points"}; reference p; RequestInfo info; // zero out the info structure; memset(&info, 0, sizeof(info)); // ... (example code for ksGetObjConstraints and ksDestroyObjConstraint would follow here) ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### Position Leader Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Illustrates how to position a leader with specified parameters, including its starting point, arrow type, text, and polyline. It uses `memset` for initialization, `CreateArray` and `AddArrayItem` for data structures, and `PositionLeader` to create the object. ```c void PositionLeader_Example (void) { reference p; PosLeaderParam leaderPar; memset(&leaderPar, 0, sizeof(PosLeaderParam)); leaderPar.x=50; leaderPar.y=50; // начало полки leaderPar.arrowType = 1; // тип стрелки leaderPar.dirX="1; // полка влево) leaderPar.pText = CreateArray(CHAR_STR_ARR,0); AddArrayItem(leaderPar.pText, "1, 11, 3); leaderPar.pPolyline =CreateArray(POLYLINE_ARR,0); reference pPoly = CreateArray(POINT_ARR , 0); MathPointParam mPar; mPar.x = 10; mPar.y = 10; AddArrayItem(pPoly , "1, &mPar, sizeof(mPar)); AddArrayItem(leaderPar.pPolyline , "1, &pPoly, sizeof(pPoly)); mPar.x = 30; mPar.y = 10; ClearArray(pPoly); AddArrayItem(pPoly , "1, &mPar, sizeof(mPar)); AddArrayItem(leaderPar.pPolyline , "1, &pPoly, sizeof(pPoly)); p = PositionLeader(&leaderPar); }; /* PositionLeader_Example */ ``` -------------------------------- ### FindObj Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates how to find an object at a given coordinate and highlight it. ```APIDOC ## FindObj Example ### Description This example draws two line segments and then uses `FindObj` to locate an object at specific coordinates (20, 20) within a certain tolerance (5). The found object is then highlighted. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c { reference pLine; LineSeg(0, 0, 50, 50, 1); LineSeg(50, 50, 70, 20, 1); pLine = FindObj(20, 20, 5); LightObj(pLine, 1); } ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### Database Operations: Creating and Connecting Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_095.txt This code demonstrates creating a database object, connecting to an ODBC data source, and retrieving table and column names. It iterates through tables and columns, displaying their names. The example requires the ODBC SDK to be installed. ```c //создать объект, обслуживающий базу данных reference bd = CreateDB ("ODBC_DB"); if (ConnectDB (bd, nameOBDC)) { if (GetTableName (bd, buf, 128, 'F')) { do { Message(buf); if (GetColumnName (bd, buf, buf, 128, 'F')) { do { Message(buf); } while (GetColumnName (bd, buf, buf, 128, 'N')); } } while (GetTableName (bd, buf, 128, 'N')) ; } } ``` -------------------------------- ### Marker Leader Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates the creation of a marker leader, similar to the branded leader but with a different arrow type. It initializes `MarkerLeaderParam`, adds text, and defines the polyline for the marker leader. ```c void MarkerLeader_Example (void) { reference p; MarkerLeaderParam leaderPar; memset(&leaderPar, 0, sizeof(BrandLeaderParam)); leaderPar.cText0 = 1; // число строк в знаке leaderPar.cText1 = 1; // число строк над ножкой leaderPar.cText2 = 1; // число строк под ножкой leaderPar.x=50; leaderPar.y=50; // начало полки leaderPar.arrowType = 2; // тип стрелки leaderPar.pText = CreateArray(CHAR_STR_ARR,0); AddArrayItem(leaderPar.pText, "1, п.11, 5); AddArrayItem(leaderPar.pText, "1, Ну, 3); AddArrayItem(leaderPar.pText, "1, Ту, 3); leaderPar.pPolyline =CreateArray(POLYLINE_ARR,0); reference pPoly = CreateArray(POINT_ARR , 0); MathPointParam mPar; mPar.x = 10; mPar.y = 10; AddArrayItem(pPoly , "1, &mPar, sizeof(mPar)); AddArrayItem(leaderPar.pPolyline , "1, &pPoly, sizeof(pPoly)); mPar.x = 30; mPar.y = 10; ClearArray(pPoly); AddArrayItem(pPoly , "1, &mPar, sizeof(mPar)); AddArrayItem(leaderPar.pPolyline , "1, &pPoly, sizeof(pPoly)); p = MarkerLeader(&leaderPar); }; /* MarkerLeader_Example */ ``` -------------------------------- ### ksViewGetObjectArea Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates how to get the area of the selected objects in the current view and display a message. ```APIDOC ## ksViewGetObjectArea Example ### Description This example retrieves the area of selected objects in the current view. If an area is found, it's temporarily stored, highlighted, and a message is displayed. The highlighting is then removed. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c // define selection group reference gr = ksViewGetObjectArea(); if (gr) { // place temporary group in the model StoreTmpGroup(gr); // highlight LightObj(gr, 1); Message("Selection Area"); // turn off highlighting LightObj(gr, 0); } else Message("No group found"); ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### GetObjGabaritRect Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates how to get the bounding box (rectangular parameters) of an object. ```APIDOC ## GetObjGabaritRect Example ### Description This example creates a line segment and then retrieves its bounding box using `GetObjGabaritRect`. The retrieved rectangular parameters are stored in the `RectParam` structure. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c { reference pObj; RectParam Rect; pObj = LineSeg(10, 10, 50, 50, 1); GetObjGabaritRect(pObj, &Rect); } ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### GetViewObjCount Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates how to get the count of objects in the current view or fragment. ```APIDOC ## GetViewObjCount Example ### Description This example creates four line segments and then retrieves and displays the count of objects present in the current view. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c void GetViewObjCount_Example (void) { long n; char buf[80]; LineSeg(20, 10, 20, 30, 1); LineSeg(20, 30, 40, 30, 1); LineSeg(40, 30, 40, 10, 1); LineSeg(40, 10, 20, 10, 1); n = GetViewObjCount(0); // in the current view/fragment sprintf (buf,"Number of objects=%5d"); Message(buf); }; ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### ksSetObjConstraint Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates how to set an object constraint, specifically "equality of radii of two arcs/circles." ```APIDOC ## ksSetObjConstraint Example ### Description This example demonstrates how to set a constraint between two objects, specifically "equality of radii of two arcs/circles." It prompts the user to select two such objects using the cursor and then applies the constraint. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c // Set constraint "equality of radii of two arcs/circles" reference p; RequestInfo info; // zero out the info structure; memset(&info, 0, sizeof(info)); double x, y; info.prompt = "Select the first arc or circle"; int j = Cursor (&info, &x ,&y, 0); if (j) { if (ExistObj(p = FindObj (x, y, 1e6))) { info.prompt = "Select the second arc or circle"; j = Cursor (&info, &x ,&y, 0); reference p1; if (j) { if (ExistObj (p1 = FindObj (x, y, 1e6))) { ConstraintParam par; memset (&par, 0, sizeof (par)); par.constrType = CONSTRAINT_EQUAL_RADIUS; par.partner = p1; ksSetObjConstraint (p, &par); } } } } ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### Create and Edit View Object (Positional Leader) Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_093.txt This example shows how to create a positional leader view object interactively, highlight it, and then edit it. It demonstrates the workflow for creating and modifying such objects using `ksCreateViewObject` and `ksEditViewObject`. ```cpp ksCreateViewObject, ksEditViewObject // создать объект в интерактивном режиме (позиционная линия выноски) reference posLeader = ksCreateViewObject(POSLEADER_OBJ ); if (posLeader){ LightObj(posLeader, 1); Message("Позиционная линия выноски"); LightObj(posLeader, 0); if (ksEditViewObject(posLeader)) { LightObj(posLeader, 1); Message("Отредактированная позиционная линия выноски"); LightObj(posLeader, 0); } } ``` -------------------------------- ### Iterator_Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates how to iterate through all objects in the current document and highlight each one sequentially. ```APIDOC ## Iterator_Example ### Description This function demonstrates how to use an iterator to traverse all objects within the current document. Each object is highlighted sequentially, and its count is displayed. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c void Iterator_Example (void) { reference itAllObj; reference obj; int count = 0; char buf[128]; // Create iterator itAllObj = CreateIterator(ALL_OBJ , 0); if (itAllObj) { if (ExistObj(obj = MoveIterator(itAllObj, 'F'))) { // find the first object and the next in the loop do { LightObj(obj, 1); count ; sprintf(buf,"index = %d", count); Message(buf); LightObj(obj, 0); } while (ExistObj (obj = MoveIterator (itAllObj, 'N')))); } } // Delete iterator DeleteIterator(itAllObj); }; ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### Group Management with NewGroup and EndGroup Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Provides an example of creating and managing object groups using `NewGroup` and `EndGroup`. Objects like lines and circles are added to a group, and the group can later be referenced and manipulated. ```c void NewGroup_Example (void) { reference gr ; double x,y,m,ang; Phantom FANTOM; gr = NewGroup(1); /* задание группы объектов */ LineSeg ("15, 0, 15, 0, 3); /* объекты записываются */ LineSeg ( 0, "15, 0, 15, 3); /* во временный список */ Circle (0, 0, 10, 1); EndGroup(); /* закончить формирование группы */ /* ввод точки с отображением фантома и копирование группы*/ FANTOM.phType=1; FANTOM.type1.gr=gr; FANTOM.type1.xBase=0; FANTOM.type1.yBase=0; FANTOM.type1.scale=1; FANTOM.type1.ang=0; ``` -------------------------------- ### Get and Destroy Object Constraints in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example snippet is a prelude to demonstrating how to retrieve and destroy object constraints. It initializes an array of constraint type names and sets up a RequestInfo structure for user interaction, likely for selecting objects to query or modify constraints. ```c static char *str [] = {"фиксировать точку", "точка на кривой", "горизонталь", "вертикаль", "параллельность двух прямых или отрезков", "перпендикулярность двух прямых или отрезков", "равенство длин двух отрезков", "равенство радиусов двух дуг/окружностей", "выравнивать две точки по горизонтали", "выравнивать две точки по вертикали", "совпадение двух точек"}; reference p; RequestInfo info; memset(&info, 0, sizeof(info)); ``` -------------------------------- ### Handle Object Area Selection in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example shows how to get the currently selected object area, store it as a temporary group, highlight it, and display a message. It uses ksViewGetObjectArea, StoreTmpGroup, LightObj, and Message functions. ```c reference gr = ksViewGetObjectArea(); if (gr) { StoreTmpGroup(gr); LightObj(gr, 1); Message("Область выделения"); LightObj(gr, 0); } else Message("Группы нет"); ``` -------------------------------- ### ksGetDocVariableArray and ksSetDocVariableArray Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates how to retrieve, modify, and set document variables. ```APIDOC ## ksGetDocVariableArray, ksSetDocVariableArray Example ### Description This example shows how to get the array of document variables for the current graphical document, iterate through them, display their properties, modify their values and notes, and then set the modified array back to the document. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c // get a pointer to the current graphical document reference doc = ksGetCurrentDocument(1); // 0 " any document, // 1" only graphical document // 2 " only specification if (doc) { char buf [250]; // get the array of external document variables reference arrayVar = ksGetDocVariableArray(doc); //pointer to the document // or insertion of a fragment for (int i=0, count = GetArrayCount(arrayVar); i < count; i) { VariableParam par; // get the current variable GetArrayItem(arrayVar, i, &par, sizeof(VariableParam)); sprintf(buf, "name = %s\nvalue = %f\nnote = %s", par.name, par.value, par.note); Message(buf); par.value = 100; strcat(par.note, "!!!"); // replace the current variable in the array SetArrayItem(arrayVar, i, &par, sizeof(VariableParam)); } // replace the values of external document variables ksSetDocVariableArray (doc, // pointer to the document or fragment insertion arrayVar, // pointer to the dynamic array VARIABLE_ARR 1); // change comments } else Error ("Document must be graphical"); ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### Brand Leader Creation Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Shows how to create a branded leader, defining text lines, position, arrow type, and polyline. It initializes `BrandLeaderParam`, adds text strings to `pText`, and constructs the polyline for the leader. ```c void BrandLeader_Example (void) { reference p; BrandLeaderParam leaderPar; memset(&leaderPar, 0, sizeof(BrandLeaderParam)); leaderPar.cText0 = 1; // число строк в знаке leaderPar.cText1 = 1; // число строк над ножкой leaderPar.cText2 = 1; // число строк под ножкой leaderPar.x=50; leaderPar.y=50; // начало полки leaderPar.arrowType = 1; // тип стрелки leaderPar.dirX="1; // полка влево leaderPar.pText = CreateArray(CHAR_STR_ARR,0); AddArrayItem(leaderPar.pText, "1, п.11, 5); AddArrayItem(leaderPar.pText, "1, Ну, 3); AddArrayItem(leaderPar.pText, "1, Ту, 3); leaderPar.pPolyline =CreateArray(POLYLINE_ARR,0); reference pPoly = CreateArray(POINT_ARR , 0); MathPointParam mPar; mPar.x = 10; mPar.y = 10; AddArrayItem(pPoly , "1, &mPar, sizeof(mPar)); AddArrayItem(leaderPar.pPolyline , "1, &pPoly, sizeof(pPoly)); mPar.x = 30; mPar.y = 10; ClearArray(pPoly); AddArrayItem(pPoly , "1, &mPar, sizeof(mPar)); AddArrayItem(leaderPar.pPolyline , "1, &pPoly, sizeof(pPoly)); p = BrandLeader(&leaderPar); }; /* BrandLeader_Example */ ``` -------------------------------- ### ReleaseReference Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates the use of ReleaseReference to deallocate memory associated with an object's reference. ```APIDOC ## ReleaseReference Example ### Description This example demonstrates how to create a line segment, highlight it, and then release its reference using `ReleaseReference`. After calling `ReleaseReference`, the pointer to the object becomes invalid. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c reference p = LineSeg (100, 50, 200, 50, 1); LightObj (p, 1); / the pointer to the object is released, / after calling ReleaseReference, the object p cannot be accessed ReleaseReference (p); LightObj (p, 0); // an error is triggered "Object not found in the current document" MessageBoxResult(); ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### Create and Transform Annotation Arc by Point Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_093.txt Demonstrates the creation of an annotation arc using specified points and parameters, including arrow styles. The example shows how to transform the arc and then delete it. ```cpp AnnArcByPoint //аннотационная дуга c большими стрелками изнутри (7мм) reference p = AnnArcByPoint (30, 40, 20, 30, 20, 50, 40, "1, 6, 6, 1); Message ("аннотационная дуга"); //трансформируем объект Mtr ("10,"10,0, 2); TransformObj (p); DeleteMtr (); Message ("удалим"); DeleteObj (p); ``` -------------------------------- ### Iterate Through All Objects in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example demonstrates iterating through all objects in the current document using CreateIterator, MoveIterator, ExistObj, and DeleteIterator. It highlights each object and displays its sequential number. LightObj and sprintf are used for visualization and message formatting. ```c void Iterator_Example (void) { reference itAllObj; reference obj; int count = 0; char buf[128]; itAllObj = CreateIterator(ALL_OBJ , 0); if (itAllObj) { if (ExistObj(obj = MoveIterator(itAllObj, 'F'))) { do { LightObj(obj, 1); count ; sprintf(buf,"номер = %d", count); Message(buf); LightObj(obj, 0); } while (ExistObj (obj = MoveIterator (itAllObj, 'N'))); } } DeleteIterator(itAllObj); }; ``` -------------------------------- ### Create Regular Polygon with Parameters Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_093.txt Demonstrates how to create a regular polygon with specified parameters such as the number of vertices, center coordinates, radius, and orientation. It also shows how to add custom corner parameters for fillets or chamfers. ```cpp ksRegularPolygon RegularPolygonParam par; par.count= 8; // количество вершин многоугольника par.xc= 100; // центр окружности par.yc= 100; par.ang= 35; // угол первой вершины par.radius= 40; // радиус окружности par.describe= 1; // признак описанного многоугольника. par.style= 1; // стиль линии par.pCorner= ::CreateArray (CORNER_ARR, 0); // динамический массив // структур параметров углов CORNER_ARR CornerParam cpar; // структура параметров угла cpar.index = 5; // индекс угла cpar.fillet = 0; // признак фаски cpar.l1 = 40; // длина фаски 1 сегмента cpar.l2 = 45; // длина фаски 2 сегмента ::AddArrayItem(par.pCorner, "1, &cpar, sizeof(CornerParam)); // добавить угол в массив cpar.index = 2; // индекс угла cpar.fillet = 1; // признак скругления cpar.l1 = 20; // радиус cpar.l2 = 20; // радиус ::AddArrayItem(par.pCorner, "1, &cpar, sizeof(CornerParam)); // добавить угол в массив ::ksRegularPolygon(&par, 3);// создаётся многоугольник с осями ``` -------------------------------- ### Center Marker Creation Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates the creation of a center marker object using `ksCentreMarker`. It initializes `CentreParam` with properties like position, type, and tail lengths, then calls the creation function. ```c CentreParam cPar;// структура параметров объекта "обозначение центра" ::memset(&cPar, 0, sizeof(cPar)); cPar.x = 50; // точка привязки cPar.y = 50; cPar.type = 2; // тип обозначения центра " две оси cPar.lenXpTail = 40; // длина "хвостиков" cPar.lenXmTail = 60; cPar.lenYpTail = 20; cPar.lenYmTail = 45; ::ksCentreMarker(&cPar); // создать объект "обозначение центра" ``` -------------------------------- ### SaveGroup Example Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates how to create a group of objects, add line segments to it, and optionally save the group to the model. ```APIDOC ## SaveGroup Example ### Description This example shows how to define a group of objects, add line segments to it, and then save the group to the current model if the user confirms. ### Method Not applicable (example code) ### Endpoint Not applicable (example code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c char name[40]; gr = NewGroup(0); /* define object group */ LineSeg (10, 10, 10, 20, 1); /* objects are written */ LineSeg (10, 20, 40, 20, 1); /* into the model of the current view */ LineSeg (40, 20, 40, 30, 1); LineSeg (40, 30, 70, 30, 1); LineSeg (70, 30, 70, 10, 1); LineSeg (70, 10, 10, 10, 1); EndGroup(); /* finish group formation */ LightObj(gr, 2);/* highlight group */ if (Yes_No(Save group to model?)) { ReadString(Group name, name, 40); SaveGroup(gr, name); } LightObj(gr, 0);/* remove group highlighting */ ``` ### Response #### Success Response (200) No explicit response defined, actions are performed directly. ``` -------------------------------- ### Kompas GetHWindow Example (C++) Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_095.txt Demonstrates how to retrieve the handle to the main Kompas window using GetHWindow and display a message box. This function is useful for interacting with the main application window. It depends on the Kompas API function GetHWindow and the standard Windows API function MessageBox. ```cpp void GetHWindow_Example ( void ) { /* выдача сообщения в главном окне */ MessageBox( GetHWindow( ), Текст заголовка окна, Текст сообщения, MB_ICONINFORMATION ); }; ``` -------------------------------- ### Create Leader with Polyline and Text Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt Demonstrates the creation of a leader object, including defining its text and polyline components. It utilizes functions like `CreateArray`, `AddArrayItem`, and `Leader`. Assumes `tLinePar` is a pre-defined structure. ```c AddArrayItem(leaderPar.pTextline, "1, &tLinePar, sizeof(tLinePar)); leaderPar.pPolyline =CreateArray(POLYLINE_ARR,0); reference pPoly = CreateArray(POINT_ARR , 0); //две ножки по одной точке в каждой MathPointParam mPar; mPar.x = 10; mPar.y = 10; AddArrayItem(pPoly , "1, &mPar, sizeof(mPar)); AddArrayItem(leaderPar.pPolyline , "1, &pPoly, sizeof(pPoly)); mPar.x = 30; mPar.y = 10; ClearArray(pPoly); AddArrayItem(pPoly , "1, &mPar, sizeof(mPar)); AddArrayItem(leaderPar.pPolyline , "1, &pPoly, sizeof(pPoly)); p = Leader(&leaderPar); }; /* Leader_Example */ ``` -------------------------------- ### Release Object Reference in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example illustrates how to create a line segment, highlight it, and then release its reference using ReleaseReference. After releasing, attempting to access the object will result in an error. LightObj and MessageBoxResult are used for feedback. ```c reference p = LineSeg (100, 50, 200, 50, 1); LightObj (p, 1); ReleaseReference (p); LightObj (p, 0); MessageBoxResult(); ``` -------------------------------- ### Kompas ksDrawKompasDocument Example (C++) Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_095.txt Illustrates how to use ksDrawKompasDocument to display a Kompas document (e.g., a slide) within a custom window. It involves creating a TWindow, setting its attributes, creating the window, and then drawing the document. Dependencies include TWindow, GetWindowPtr, and ksDrawKompasDocument. ```cpp TWindow *st = new TWindow (GetWindowPtr( ( HWND )GetHWindow( ) ), 0 ); st">Attr.X =300; st">Attr.Y =30; st">Attr.W =170; st">Attr.H =160; st">Create( ); //создали окно, в котором хотим отрисовать слайд ksDrawKompasDocument( ( void* ) st">HWindow, // несущее окно "d:\\0\\fg1.frw" ); // полное имя файла документа Message( "Слайд КОМПАС" ); delete st; ``` -------------------------------- ### Find Object by Coordinates in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example draws two line segments and then uses FindObj to locate an object at a specific coordinate with a given search radius. The found object is then highlighted. ```c reference pLine; LineSeg(0, 0, 50, 50, 1); LineSeg(50, 50, 70, 20, 1); pLine = FindObj(20, 20, 5); LightObj(pLine, 1); ``` -------------------------------- ### Create and Save Group of Objects in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example demonstrates how to create a new group of objects, add line segments to it, and optionally save the group with a user-defined name. It utilizes functions like NewGroup, LineSeg, EndGroup, LightObj, Yes_No, ReadString, and SaveGroup. ```c char name[40]; gr = NewGroup(0); LineSeg (10, 10, 10, 20, 1); LineSeg (10, 20, 40, 20, 1); LineSeg (40, 20, 40, 30, 1); LineSeg (40, 30, 70, 30, 1); LineSeg (70, 30, 70, 10, 1); LineSeg (70, 10, 10, 10, 1); EndGroup(); LightObj(gr, 2); if (Yes_No("Сохранять группу в модели?")) { ReadString("Имя группы", name, 40); SaveGroup(gr, name); } LightObj(gr, 0); ``` -------------------------------- ### Define and Apply Hatch Pattern Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_093.txt This example demonstrates how to define a closed boundary using line segments and then apply a hatch pattern to this area. The `EndObj()` function is used to finalize the hatch object. ```cpp Hatch void Hatch_Example (void) { reference p; LineSeg (10, 10, 10, 20, 1); LineSeg (10, 20, 40, 20, 1); LineSeg (40, 20, 40, 30, 1); LineSeg (40, 30, 70, 30, 1); LineSeg (70, 30, 70, 10, 1); LineSeg (70, 10, 10, 10, 1); Hatch(1, 45, 3, 0, 0,0); /* определение штриховки */ LineSeg (10, 10, 10, 20, 1); LineSeg (10, 20, 40, 20, 1); LineSeg (40, 20, 40, 30, 1); LineSeg (40, 30, 70, 30, 1); LineSeg (70, 30, 70, 10, 1); LineSeg (70, 10, 10, 10, 1); p = EndObj(); /* закончить формирование штриховки */ }; /* Hatch_Example */ ``` -------------------------------- ### Iterate Through Open Documents in C++ Source: https://context7.com/dwnmf/kompas-api-docv2/llms.txt Provides a C++ code example to iterate through all currently open Kompas documents. It retrieves the total count of open documents and then loops through each document, printing its index and name. This function requires an active Kompas application instance. ```cpp IApplication* pApp = nullptr; // ... obtain application instance ... IDocumentsCollection* pDocs = nullptr; pApp->get_Documents(&pDocs); if (pDocs) { long docCount = 0; pDocs->get_Count(&docCount); printf("Open documents: %ld\n", docCount); for (long i = 0; i < docCount; i++) { IKompasDocument* pDoc = nullptr; pDocs->get_Item(i, &pDoc); if (pDoc) { BSTR name = nullptr; pDoc->get_Name(&name); wprintf(L" [%ld] %s\n", i, name); SysFreeString(name); pDoc->Release(); } } pDocs->Release(); } ``` -------------------------------- ### Get Bounding Box of an Object in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example creates a line segment and then retrieves its bounding box dimensions using GetObjGabaritRect. The RectParam structure will contain the bounding box information. ```c reference pObj; RectParam Rect; pObj = LineSeg(10, 10, 50, 50, 1); GetObjGabaritRect(pObj, &Rect); ``` -------------------------------- ### Get Object Count in Current View in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example demonstrates how to draw several line segments and then retrieve the count of objects present in the current view or fragment using GetViewObjCount. The count is then displayed in a message box. ```c void GetViewObjCount_Example (void) { long n; char buf[80]; LineSeg(20, 10, 20, 30, 1); LineSeg(20, 30, 40, 30, 1); LineSeg(40, 30, 40, 10, 1); LineSeg(40, 10, 20, 10, 1); n = GetViewObjCount(0); sprintf (buf,"Количество объектов=%5d); Message(buf); }; ``` -------------------------------- ### Kompas Library Entry and File Choice (C++) Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_095.txt Handles the library entry point (LibraryEntry) for Kompas, allowing initialization of the custom file preview function and user file selection. It uses Kompas API functions like ksInitFilePreviewFunc, ksChoiceFile, and Message. Input is an unsigned int command; output is through messages or file selection. ```cpp extern "C" void far __export __pascal LibraryEntry( unsigned int com ){ switch ( com ) { case 1: { //установим адрес нашей функции просмотра ksInitFilePreviewFunc( MyPreviewFunc ); char fileName[250]; //выберем файл if( ( ksChoiceFile( 0,"Все файлы (*.* )|*.*|", fileName, 250, 1 ) ) != 0 ) Message( fileName ); // обнулим адрес ksInitFilePreviewFunc( 0 ); // выберем файл if( ( ksChoiceFile( 0,"Все файлы (*.* )|*.*|", fileName, 250, 1 ) ) != 0 ) Message( fileName ); break; } } } ``` -------------------------------- ### Get Curve Perimeter and Inertia Properties Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_093.txt Demonstrates how to get the perimeter and calculate inertia properties (like area and mass properties) for various types of curves and contours. It involves user selection of an object and checking its type before calling the respective functions. ```cpp reference pObj; RequestInfo info; double x, y; memset(&info, 0, sizeof(info)); info.prompt = "Укажите кривую"; int j = Cursor(&info, &x ,&y, 0); if (j) { if(ExistObj(pObj = FindObj(x, y, 1e6))){ int type = GetObjParam( pObj,0,0,0); //указатель на графический объект if (type == CIRCLE_OBJ || type == ARC_OBJ || type == NURBS_OBJ || type == LINESEG_OBJ || type == BEZIER_OBJ || type == CONTOUR_OBJ || type == POLYLINE_OBJ || type == ELLIPSE_OBJ || type == ELLIPSE_ARC_OBJ || ``` -------------------------------- ### Set Equal Radius Constraint for Arcs/Circles in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example shows how to set an 'equal radius' constraint between two selected arcs or circles. It uses Cursor to get user input for selecting the objects, FindObj to identify them, and ksSetObjConstraint with CONSTRAINT_EQUAL_RADIUS. ```c reference p; RequestInfo info; memset(&info, 0, sizeof(info)); double x, y; info.prompt = "Укажите первую дугу или окружность"; int j = Cursor (&info, &x ,&y, 0); if (j) { if (ExistObj(p = FindObj (x, y, 1e6))) { info.prompt = "Укажите вторую дугу или окружность"; j = Cursor (&info, &x ,&y, 0); reference p1; if (j) { if (ExistObj (p1 = FindObj (x, y, 1e6))) { ConstraintParam par; memset (&par, 0, sizeof (par)); par.constrType = CONSTRAINT_EQUAL_RADIUS; par.partner = p1; ksSetObjConstraint (p, &par); } } } } ``` -------------------------------- ### Manage Document Variables in Kompas API Source: https://github.com/dwnmf/kompas-api-docv2/blob/main/part_094.txt This example demonstrates how to get the current document, retrieve its external variables using ksGetDocVariableArray, iterate through them, display their properties, modify their values and notes, and then update the document variables with ksSetDocVariableArray. It includes error handling for non-graphic documents. ```c reference doc = ksGetCurrentDocument(1); if (doc) { char buf [250]; reference arrayVar = ksGetDocVariableArray(doc); for (int i=0, count = GetArrayCount(arrayVar); i < count; i) { VariableParam par; GetArrayItem(arrayVar, i, &par, sizeof(VariableParam)); sprintf(buf, "имя = %s\nзначение = %f\nкомментарий = %s", par.name, par.value, par.note); Message(buf); par.value = 100; strcat(par.note, "!!!"); SetArrayItem(arrayVar, i, &par, sizeof(VariableParam)); } ksSetDocVariableArray (doc, arrayVar, 1); } else Error ("Документ должен быть графическим"); ``` -------------------------------- ### Core Application Management Source: https://context7.com/dwnmf/kompas-api-docv2/llms.txt This section covers essential operations for managing the KOMPAS application instance, including connecting to the application, checking licenses, enabling invisible mode, and executing commands. ```APIDOC ## Core Application Management ### Get Application Instance and Check License This function demonstrates how to connect to a running KOMPAS application instance, make it visible, and retrieve license information, including the status of specific modules like the 3D module and the KOMPAS variant. ```cpp // Connect to KOMPAS application IApplication* pKompasApp = nullptr; HRESULT hr = CoCreateInstance( CLSID_KompasApplication, NULL, CLSCTX_LOCAL_SERVER, IID_IApplication, (void**)&pKompasApp ); if (SUCCEEDED(hr) && pKompasApp) { // Make application visible pKompasApp->put_Visible(VARIANT_TRUE); // Get license manager IApplicationLicenseManager* pLicMgr = nullptr; pKompasApp->get_LicenseManager(&pLicMgr); if (pLicMgr) { // Check if specific module is available VARIANT_BOOL isActive = VARIANT_FALSE; pLicMgr->KompasModuleActive(ksModule3D, &isActive); if (isActive == VARIANT_TRUE) { // Module is licensed and available printf("3D Module is active\n"); } // Get KOMPAS variant (Light, Standard, Professional, etc.) KompasVariantEnum variant; pLicMgr->get_KompasVariant(&variant); pLicMgr->Release(); } pKompasApp->Release(); } ``` ### Enable KOMPAS-Invisible Mode with License Key This function shows how to enable KOMPAS-Invisible mode by providing a license key and signature, which is crucial for running KOMPAS applications in a headless or background environment. ```cpp IApplication* pApp = nullptr; // ... obtain application instance ... IApplicationLicenseManager* pLicMgr = nullptr; pApp->get_LicenseManager(&pLicMgr); if (pLicMgr) { // Register KOMPAS-Invisible license BSTR key = SysAllocString(L"YOUR-LICENSE-KEY-HERE"); BSTR signature = SysAllocString(L"YOUR-SIGNATURE-HERE"); VARIANT_BOOL result = VARIANT_FALSE; pLicMgr->EnableKompasInvisible(key, signature, &result); if (result == VARIANT_TRUE) { printf("KOMPAS-Invisible mode enabled successfully\n"); } else { printf("Failed to enable KOMPAS-Invisible mode\n"); } SysFreeString(key); SysFreeString(signature); pLicMgr->Release(); } ``` ### Execute KOMPAS Commands Programmatically This function allows developers to programmatically execute built-in KOMPAS commands, such as creating new documents or rebuilding the active document. It also includes a check to determine if a command is enabled before execution. ```cpp // Execute a KOMPAS command (e.g., open new document) IApplication* pApp = nullptr; // ... obtain application instance ... // Command IDs from KOMPAS API constants const long CMD_FILE_NEW_DOCUMENT = 20100; const long CMD_VIEW_REDRAW = 20301; const long CMD_DOCUMENT_REBUILD = 20401; // Execute command (post=FALSE for synchronous execution) VARIANT_BOOL result = VARIANT_FALSE; pApp->ExecuteKompasCommand(CMD_FILE_NEW_DOCUMENT, VARIANT_FALSE, &result); // Check if command is available before execution VARIANT_BOOL isEnabled = VARIANT_FALSE; pApp->IsKompasCommandEnable(CMD_DOCUMENT_REBUILD, VARIANT_FALSE, &isEnabled); if (isEnabled == VARIANT_TRUE) { pApp->ExecuteKompasCommand(CMD_DOCUMENT_REBUILD, VARIANT_FALSE, &result); } ``` ```