# Packaging Modeling Using the SolidWorks API

One of the tasks encountered in the development of new products is the task of packaging their packaging.

As an illustration of this statement, we will give an example in which even IT specialists faced such a task. Just at the time of writing this article, the programmers of one of the divisions of Special Technology Center LLC were selecting components for a complex of radio-electronic equipment, which included servers and workstations. As a designer, at that moment I had to take part in the choice of containers for laying spare parts (the first image is under the cut). How such tasks can be solved – see below.

To select a box, you need to know the dimensions of the products to be packed, and then arrange them.

To date, packing problems have already been solved in a number of studies. In the terminology of the theory of algorithms, these problems belong to the class of NP-complete problems that do not have exact algorithms for solving it in polynomial time [1]. An example of solving this problem using a heuristic algorithm can also be found in the work [2]and the application of a special case of the heuristic algorithm – the genetic algorithm – can be seen in the work [3]. Many of these solutions involve the development of applications that visualize the results of algorithms. However, the listed sources do not mention the transfer of the results of such programs to the SolidWorks CAD system (or other system with similar functionality) for further design documentation. A fragment of the packaging drawing, designed in the Compass program, is shown below in the figure.

Another reason that prompted the author to write this article is the time spent by the developer when looking for methods for solving typical programming problems using the SolidWorks API. The API documentation of the specified program is in English, and examples of solving such problems are often found on English-language forums.

1. Show the fundamental possibility of packaging modeling using the SolidWork API.
2. Demonstrate some practical examples of solving typical programming problems.

Separate examples related to the second task were considered in the article [

4

].

We formalize the description of the initial data for modeling.

There are many n placed objects (products), i=1, 2,…, n. Every i-th the block is characterized by three parameters – dimensions along the axes , And . All products are offset relative to the origin of the assembly 3D model by non-negative values:

along the axis X:

along the axis Y:

along the axis Z:

We also add one condition to the description of the problem, which should be taken into account when modeling. In some of the packages, there is the task of preserving the product using silica gel. Silica gel in bags is placed in polyethylene covers, which are then sealed. These bags have a certain volume. For uniform laying, it is proposed to use foam pads with cutouts, which are superimposed on the places where the silica gel was laid and fixed with a stretch film.

Thus, there are many m placed gaskets, j=1, 2,…, m.

Each j-th the gasket is similarly characterized by dimensions along the axes , And , a non-negative offset along each of the axes, and a notch along one of the axes. The dimensions of the cutout are set as shown in the three figures. The use of pads is optional.

Also along the walls of the box in which the products are packed, foam pads can be installed.

These gaskets are modeled in one piece, which is also given in three dimensions. , And axially, wall thickness S and offset in the negative direction relative to the axes:

along the axis X:

по оси Y:

по оси Z:

Помимо этого в сборке может размещаться модель ящика, задаваемая отрицательными смещениями по осям, по аналогии с предыдущей прокладкой. Ящик спроектирован в программе, рассмотренной в статье [4].

This formalized description is saved as a list in an ANSI encoded text file. This encoding is needed for correct display of reading results using C++\CLI.

The syntax for writing in a text file is given below.

#Путь к результатам
Путь к папке для сохранения результатов работы
Наименование файла компоновки (без расширения)
#Конец
#Упаковываемые изделия
Наименование упаковываемого изделия (без расширения)
0 – без группы, больше нуля – номер группы упаковываемых одинаковых изделий
Lx
Ly
Lz
Dx
Dy
Dz
#Конец
#Пенопласт
Наименование прокладки (без расширения)
Lx
Ly
Lz
X, Y или Z – ось, вдоль которой выполнен вырез
d1
d2
L1
L2
Dx
Dy
Dz
#Конец
#Пенопласт у стенок
Lx
Ly
Lz
S
Dx
Dy
Dz
#Конец
#Ящик
Путь к файлу 3D-модели сборки ящика
Dx
Dy
Dz
#Конец

To implement the simulation of this package, an application was developed in the C++\CLI language. The application reads the aforementioned text file, the path to which is passed to the program via a command line argument. Application developed in Microsoft Visual Studio IDE 2022 (64-bit). The program was run on a computer running Windows 10. The computer had the following specifications: Intel® Core(TM) i5-7600 CPU 3.50 GHz, RAM 16 GB. CAD system – SolidWorks 2019 (64-bit). The simulation time for one layout consisting of seven packaged items, one gasket, one gasket against the walls of the box and the box itself was 1 min 34 s.

If we consider the problem in an enlarged way, then the sequence of modeling is as follows:

2. Copying the necessary part template files to the folder with the simulation result.
3. Inserting Models into a Layout.

In turn, the insertion of models into the layout is implemented in the following sequence (on the example of models of packaged products), presented below. In parentheses are the tasks, the solution of which was considered in the article. [

4

].

1. Accessing an object of a type SldWorks^ (see article).
2. Disabling application visibility (see macro acceleration tasks in the article)
3. Opening a 3D layout model file.
4. Insertion in the cycle of 3D models of packaged products.
5. Specifies mates for the inserted model.

The insertion of 3D models of packaged products is illustrated by a fragment of the program code of the corresponding function.

//Значения переменных
// swApp - объект SldWorks^, переданный по ссылке в функцию
IModelDoc2^ swModel;
int ok; //Результат изменения свойств. Функция SetActiveConfigProperty рассмотрена в статье [4].
ModelView^ modView;
DesignTable^ DesTbl; //Таблица параметров
bool bool_D; //Результаты обращения к таблице параметров
AssemblyDoc^ assemb;
ModelDocExtension^ swModelDocExt;

//Откроем файл модели груза
swApp->OpenDoc6(gcnew System::String(str_Cargo_output_full_path.c_str()), 1, 0, "", swErrors, swWarnings);

//Проведем процедуры инициализации переменных для работы со свойствами
swApp->ActivateDoc2(gcnew System::String(sPackaged_cargo[i].str_Name.c_str()) +".SLDPRT", false, longstatus);
swModel = (IModelDoc2^)swApp->ActiveDoc;

//Пропишем в документ необходимые свойства
//Х – размер по оси Х
s_property = "X";
ok = Packing_wizard::SetActiveConfigProperty(swModel, s_property, mylib::to_string(sPackaged_cargo[i].dbl_Lx), 1);
//Y – размер по оси Y
s_property = "Y";
ok = Packing_wizard::SetActiveConfigProperty(swModel, s_property, mylib::to_string(sPackaged_cargo[i].dbl_Ly), 1);
//Z – размер по оси Z
s_property = "Z";
ok = Packing_wizard::SetActiveConfigProperty(swModel, s_property, mylib::to_string(sPackaged_cargo[i].dbl_Lz), 1);

//Отключаем регенерацию графического окна
modView = (ModelView^)swModel->ActiveView;
modView->EnableGraphicsUpdate = false; //Отключаем регенерацию

//Получаем доступ к таблице параметров
DesTbl = (DesignTable^)swModel->GetDesignTable();
bool_D = DesTbl->Attach();

//Обновляем таблицу параметров и отключаемся от нее
bool_D = DesTbl->UpdateTable(2, true);
DesTbl->Detach();

//Сохраняем документ
swModel->Save();

//Активируем модель компоновки
swApp->ActivateDoc2(gcnew System::String(sOutput_data.str_Name.c_str()) + ".SLDASM", false, longstatus);

//Готовим интерфейс для вставки модели
assemb = (AssemblyDoc^)swApp->ActiveDoc;

//Вставляем модель за пределами максимальных габаритов ящика 2850х1500х2000 мм

//Закрываем модель груза
swApp->CloseDoc(gcnew System::String((sPackaged_cargo[i].str_Name + ".SLDPRT").c_str()));

//Активируем модель компоновки
swApp->ActivateDoc2(gcnew System::String(sOutput_data.str_Name.c_str()) + ".SLDASM", false, longstatus);
swModel = swApp->IActiveDoc2;

//Перестраиваем модель компоновки
swModel->EditRebuild3();

//Если компонент, вставленный в сборку, первый, отключаем его фиксацию
if (i == 0)
{
swModel = (ModelDoc2^)swApp->ActiveDoc;
swModelDocExt = swModel->Extension;
swModelDocExt->SelectByID2(gcnew System::String((sPackaged_cargo[i].str_Name + "-1@" + sOutput_data.str_Name).c_str()),"COMPONENT", 0, 0, 0, false, 0, nullptr, 0);
assemb->UnfixComponent();
swModel->ClearSelection2(true);
}


There are several things to note here. One of them is that in order to be able to set mates with non-negative values ​​between the planes of the coordinate system of the 3D model of the assembly and the faces of the inserted products, the products are inserted with coordinates lying on the border of the internal dimensions of the box. Another point is to insert a component into an assembly using the method AddComponent it must be previously opened by the method OpenDoc6. Some of the methods shown in the code have already been given in the article. [4].

Let us now consider the accepted approaches to automatically specifying mates in the assembly model.

To implement them in 3D models of products inserted into the assembly, a special markup was previously performed using reference geometry.

Consider the first method of automatically specifying mates and the first method of markup shown in the figure below.

dot O the origin of coordinates is indicated. Dot one lies on the axis Xdot 2 on axle Ydot 3 – on the axis Z.

points one3 in the assembly coordinate system will have coordinates with indices one3 respectively.

To automatically set mates between the planes of the assembly coordinate system and the surfaces of the packed products, it is necessary to select using API methods. To select surfaces, it is enough to specify the coordinates of any point located on the surface and not lying on the edges of the 3D model.

One option is to specify the points that lie in the center of the three segments connecting the points one3.

When specifying mates, the 3D model of the packaged product will move with its faces parallel to the planes of the assembly coordinate system. Therefore, the points in the middle of the segments will have the following coordinates.

A point used to specify mates along an axis X:

A point used to specify mates along an axis Y:

A point used to specify mates along an axis Z:

Here is a program code illustrating the measurement of coordinates of points one3 and specifying mates along the axis X. This code is a continuation of the code above.

        //Координаты точек
Coordinates sC_point_1; //Точка 1 компонента
Coordinates sC_point_2; //Точка 2 компонента
Coordinates sC_point_3; //Точка 3 компонента
Coordinates sC_X; //Характерная точка для задания сопряжения по оси X
Coordinates sC_Y; //Характерная точка для задания сопряжения по оси Y
Coordinates sC_Z; //Характерная точка для задания сопряжения по оси Z
AssemblyDoc^ swAssemblyDoc;

//Измерение координат точек
//Получение координат точки 1 во вставляемой детали
swModelDocExt->SelectByID2(gcnew System::String(("Точка1@"+ sPackaged_cargo[i].str_Name + "-1@" + sOutput_data.str_Name).c_str()), "DATUMPOINT", 0, 0, 0, false, 0, nullptr, 0);
Measure = swModelDocExt->CreateMeasure();
Measure->ArcOption = 0;
Measure->Calculate(nullptr);
sC_point_1.dbl_X = Measure->X;
sC_point_1.dbl_Y = Measure->Y;
sC_point_1.dbl_Z = Measure->Z;
swModel->ClearSelection2(true);
//Получение координат точки 2
swModelDocExt->SelectByID2(gcnew System::String(("Точка2@" + sPackaged_cargo[i].str_Name + "-1@" + sOutput_data.str_Name).c_str()), "DATUMPOINT", 0, 0, 0, false, 0, nullptr, 0);
Measure = swModelDocExt->CreateMeasure();
Measure->ArcOption = 0;
Measure->Calculate(nullptr);
sC_point_2.dbl_X = Measure->X;
sC_point_2.dbl_Y = Measure->Y;
sC_point_2.dbl_Z = Measure->Z;
swModel->ClearSelection2(true);
//Получение координат точки 3
swModelDocExt->SelectByID2(gcnew System::String(("Точка3@" + sPackaged_cargo[i].str_Name + "-1@" + sOutput_data.str_Name).c_str()), "DATUMPOINT", 0, 0, 0, false, 0, nullptr, 0);
Measure = swModelDocExt->CreateMeasure();
Measure->ArcOption = 0;
Measure->Calculate(nullptr);
sC_point_3.dbl_X = Measure->X;
sC_point_3.dbl_Y = Measure->Y;
sC_point_3.dbl_Z = Measure->Z;
swModel->ClearSelection2(true);

//Переходим к расчету координат характерных точек
//Точка для задания смещений вдоль оси Х
sC_X.dbl_X = sC_point_3.dbl_X;
sC_X.dbl_Y = 0.5 * (sC_point_2.dbl_Y + sC_point_3.dbl_Y);
sC_X.dbl_Z = 0.5 * (sC_point_2.dbl_Z+ sC_point_3.dbl_Z);

//Переходим к указанию сопряжений
//Подготовка интерфейса
swModel = (IModelDoc2^)swApp->ActiveDoc;
swAssemblyDoc = (AssemblyDoc^)swModel;

//Сопряжения со смещениями вдоль оси Х
if (sPackaged_cargo[i].dbl_Dx == 0) //Сопряжение совпадения
{
swModelDocExt->SelectByID2("Справа", "PLANE", 0, 0, 0, false, 0, nullptr, 0);
swModelDocExt->SelectByID2("", "FACE", sC_X.dbl_X, sC_X.dbl_Y, sC_X.dbl_Z, true, 0, nullptr, 0);

swAssemblyDoc->AddMate3(0, 1, false, 0, 0, 0, 0, 0, 0, 0, 0, false, longstatus);

swModel->ClearSelection2(true);
//Перестраиваем модель компоновки
swModel->EditRebuild3();
}
else //Сопряжение на расстоянии
{
swModelDocExt->SelectByID2("Справа", "PLANE", 0, 0, 0, false, 0, nullptr, 0);
swModelDocExt->SelectByID2("", "FACE", sC_X.dbl_X, sC_X.dbl_Y, sC_X.dbl_Z, true, 0, nullptr, 0);

swAssemblyDoc->AddMate3(5, 1, false, sPackaged_cargo[i].dbl_Dx * 0.001, sPackaged_cargo[i].dbl_Dx * 0.001, sPackaged_cargo[i].dbl_Dx * 0.001, 0, 0, 0, 0, 0, false, longstatus);

swModel->ClearSelection2(true);
//Перестраиваем модель компоновки
swModel->EditRebuild3();
}



The second method of automatically specifying mates was used for positioning the 3D model of the box in the assembly. A 3D sketch was created in the box model and three points were placed on three faces using reference geometry. Thus, to indicate conjugations, it was necessary to select the planes of the coordinate system and the above points lying on the faces.

In conclusion, we note that as a result of the work done, the fundamental possibility of packaging modeling using the SolidWorks API is shown. The developed application can be used with existing applications that solve 3D packaging problems (subject to their refinement), as well as with a newly developed application that could, for example, take into account the use of silica gel for conservation in calculations. A variant of the description of information for data exchange between the developed application and applications that solve the problems of three-dimensional packaging modeling is proposed. Options for solving some typical tasks of interaction with the SolidWorks API are presented.

## Bibliographic list

1. A. A. Gilya-Zetinov, K. K. Pankratov, A. V. Khelvas Development of an algorithm for stacking pallets in a fully automated warehouse // Proceedings of the Moscow Institute of Physics and Technology .– 2019 .– vol. 11 .– No. 1(41) .– P. 20-30.
2. Nuzhnov E.V., Barlit A.V. Three-dimensional packaging based on heuristic procedures // Perspective information technologies and intelligent systems. – 2002. – No. 3. – P. 95-101.
3. Lutsan M.V., Nuzhnov E.V. Solving the problem of three-dimensional packaging with palletizing containers. Izvestiya SFU. Technical sciences .– 2014 .– No. 7 (156) .– P. 196-204.
4. Experience in using the SolidWorks API for computer-aided design of containers [Электронный ресурс] .– URL: habr.com/ru/company/stc_spb/blog/645115 .– (accessed 18.03.2022).