Salome HOME
Implementation Export STL
[modules/shaper.git] / src / ExchangePlugin / ExchangePlugin_ExportFeature.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <ExchangePlugin_ExportFeature.h>
21
22 #include <algorithm>
23 #include <iterator>
24 #include <string>
25 #ifdef _DEBUG
26 #include <iostream>
27 #include <ostream>
28 #endif
29
30
31 #include <Config_Common.h>
32 #include <Config_PropManager.h>
33
34 #include <GeomAlgoAPI_BREPExport.h>
35 #include <GeomAlgoAPI_CompoundBuilder.h>
36 #include <GeomAlgoAPI_IGESExport.h>
37 #include <GeomAlgoAPI_STEPExport.h>
38 #include <GeomAlgoAPI_STLExport.h>
39 #include <GeomAlgoAPI_Tools.h>
40 #include <GeomAlgoAPI_XAOExport.h>
41
42 #include <GeomAPI_Shape.h>
43 #include <GeomAPI_ShapeExplorer.h>
44 #include <GeomAPI_Trsf.h>
45
46 #include <Locale_Convert.h>
47
48 #include <ModelAPI_AttributeSelectionList.h>
49 #include <ModelAPI_AttributeString.h>
50 #include <ModelAPI_AttributeStringArray.h>
51 #include <ModelAPI_AttributeIntArray.h>
52 #include <ModelAPI_AttributeTables.h>
53 #include <ModelAPI_AttributeDouble.h>
54 #include <ModelAPI_Data.h>
55 #include <ModelAPI_Document.h>
56 #include <ModelAPI_Object.h>
57 #include <ModelAPI_ResultBody.h>
58 #include <ModelAPI_ResultPart.h>
59 #include <ModelAPI_ResultGroup.h>
60 #include <ModelAPI_ResultField.h>
61 #include <ModelAPI_Session.h>
62 #include <ModelAPI_Validator.h>
63 #include <ModelAPI_Tools.h>
64
65 #include <Events_InfoMessage.h>
66
67 #include <XAO_Group.hxx>
68 #include <XAO_Field.hxx>
69 #include <XAO_Xao.hxx>
70 #include <XAO_Geometry.hxx>
71
72 #include <ExchangePlugin_Tools.h>
73
74 ExchangePlugin_ExportFeature::ExchangePlugin_ExportFeature()
75 {
76 }
77
78 ExchangePlugin_ExportFeature::~ExchangePlugin_ExportFeature()
79 {
80   // TODO Auto-generated destructor stub
81 }
82
83 /*
84  * Request for initialization of data model of the feature: adding all attributes
85  */
86 void ExchangePlugin_ExportFeature::initAttributes()
87 {
88   data()->addAttribute(ExchangePlugin_ExportFeature::EXPORT_TYPE_ID(),
89     ModelAPI_AttributeString::typeId());
90   data()->addAttribute(ExchangePlugin_ExportFeature::FILE_PATH_ID(),
91     ModelAPI_AttributeString::typeId());
92   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID(),
93     ModelAPI_AttributeString::typeId());
94   data()->addAttribute(ExchangePlugin_ExportFeature::FILE_FORMAT_ID(),
95     ModelAPI_AttributeString::typeId());
96   data()->addAttribute(ExchangePlugin_ExportFeature::SELECTION_LIST_ID(),
97     ModelAPI_AttributeSelectionList::typeId());
98   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_AUTHOR_ID(),
99     ModelAPI_AttributeString::typeId());
100   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID(),
101     ModelAPI_AttributeString::typeId());
102   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_SELECTION_LIST_ID(),
103     ModelAPI_AttributeSelectionList::typeId());
104   data()->addAttribute(ExchangePlugin_ExportFeature::STL_FILE_PATH_ID(),
105     ModelAPI_AttributeString::typeId());
106   data()->addAttribute(ExchangePlugin_ExportFeature::STL_OBJECT_SELECTED(), 
107     ModelAPI_AttributeSelection::typeId());
108   data()->addAttribute(ExchangePlugin_ExportFeature::STL_DEFLECTION_TYPE(),
109    ModelAPI_AttributeString::typeId());
110   data()->addAttribute(ExchangePlugin_ExportFeature::STL_RELATIVE(), 
111     ModelAPI_AttributeDouble::typeId());
112    
113   double defelection = Config_PropManager::real("Visualization", "body_deflection");
114   real(ExchangePlugin_ExportFeature::STL_RELATIVE())->setValue(defelection);
115
116   data()->addAttribute(ExchangePlugin_ExportFeature::STL_ABSOLUTE(), 
117     ModelAPI_AttributeDouble::typeId());
118   data()->addAttribute(ExchangePlugin_ExportFeature::STL_FILE_TYPE(),
119    ModelAPI_AttributeString::typeId());
120
121   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
122     ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID());
123   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
124     ExchangePlugin_ExportFeature::STL_FILE_PATH_ID());
125   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
126     ExchangePlugin_ExportFeature::XAO_AUTHOR_ID());
127   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
128     ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID());
129   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
130     ExchangePlugin_ExportFeature::XAO_SELECTION_LIST_ID());
131
132   // to support previous version of document, move the selection list
133   // if the type of export operation is XAO
134   AttributeStringPtr aTypeAttr = string(EXPORT_TYPE_ID());
135   if (aTypeAttr->isInitialized() && aTypeAttr->value() == "XAO") {
136     bool aWasBlocked = data()->blockSendAttributeUpdated(true, false);
137     AttributeSelectionListPtr aSelList = selectionList(SELECTION_LIST_ID());
138     AttributeSelectionListPtr aXAOSelList = selectionList(XAO_SELECTION_LIST_ID());
139     if (aSelList->size() > 0 && aXAOSelList->size() == 0)
140       aSelList->copyTo(aXAOSelList);
141     aSelList->clear();
142     data()->blockSendAttributeUpdated(aWasBlocked, false);
143   }
144 }
145
146 void ExchangePlugin_ExportFeature::attributeChanged(const std::string& theID)
147 {
148   if (theID == XAO_FILE_PATH_ID()) {
149     string(ExchangePlugin_ExportFeature::FILE_PATH_ID())->setValue(
150       string(ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID())->value());
151   }
152   else if (theID == STL_FILE_PATH_ID()) {
153     string(ExchangePlugin_ExportFeature::FILE_PATH_ID())->setValue(
154       string(ExchangePlugin_ExportFeature::STL_FILE_PATH_ID())->value());
155   }
156
157 }
158
159 /*
160  * Computes or recomputes the results
161  */
162 void ExchangePlugin_ExportFeature::execute()
163 {
164   AttributeStringPtr aFormatAttr =
165       this->string(ExchangePlugin_ExportFeature::FILE_FORMAT_ID());
166   std::string aFormat = aFormatAttr->value();
167
168   AttributeStringPtr aFilePathAttr =
169       this->string(ExchangePlugin_ExportFeature::FILE_PATH_ID());
170   std::string aFilePath = aFilePathAttr->value();
171   if (aFilePath.empty())
172     return;
173
174   exportFile(aFilePath, aFormat);
175 }
176
177 void ExchangePlugin_ExportFeature::exportFile(const std::string& theFileName,
178                                               const std::string& theFormat)
179 {
180   std::string aFormatName = theFormat;
181
182   if (aFormatName.empty()) { // get default format for the extension
183     // ".brep" -> "BREP"
184     std::string anExtension = GeomAlgoAPI_Tools::File_Tools::extension(theFileName);
185     if (anExtension == "BREP" || anExtension == "BRP") {
186       aFormatName = "BREP";
187     } else if (anExtension == "STEP" || anExtension == "STP") {
188       aFormatName = "STEP";
189     } else if (anExtension == "IGES" || anExtension == "IGS") {
190       aFormatName = "IGES-5.1";
191     } else {
192       aFormatName = anExtension;
193     }
194   }
195
196   if (aFormatName == "XAO") {
197     exportXAO(theFileName);
198     return;
199   }else if (aFormatName == "STL") {
200     exportSTL(theFileName);
201     return;
202   }
203
204   // make shape for export from selected shapes
205   AttributeSelectionListPtr aSelectionListAttr =
206       this->selectionList(ExchangePlugin_ExportFeature::SELECTION_LIST_ID());
207   std::list<GeomShapePtr> aShapes;
208   for (int i = 0, aSize = aSelectionListAttr->size(); i < aSize; ++i) {
209     AttributeSelectionPtr anAttrSelection = aSelectionListAttr->value(i);
210     std::shared_ptr<GeomAPI_Shape> aCurShape = anAttrSelection->value();
211     if (aCurShape.get() == NULL)
212       aCurShape = anAttrSelection->context()->shape();
213     if (aCurShape.get() != NULL)
214       aShapes.push_back(aCurShape);
215   }
216
217   // Store compound if we have more than one shape.
218   std::shared_ptr<GeomAPI_Shape> aShape =
219     aShapes.size() == 1 ? aShapes.front() : GeomAlgoAPI_CompoundBuilder::compound(aShapes);
220
221   // Perform the export
222   std::string anError;
223   bool aResult = false;
224   if (aFormatName == "BREP") {
225     aResult = BREPExport(theFileName, aFormatName, aShape, anError);
226   } else if (aFormatName == "STEP") {
227     aResult = STEPExport(theFileName, aFormatName, aShape, anError);
228   } else if (aFormatName.substr(0, 4) == "IGES") {
229     aResult = IGESExport(theFileName, aFormatName, aShape, anError);
230   } else {
231     anError = "Unsupported format: " + aFormatName;
232   }
233
234   if (!aResult || !anError.empty()) {
235     setError("An error occurred while exporting " + theFileName + ": " + anError);
236     return;
237   }
238 }
239
240 /// Returns XAO string by the value from the table
241 static std::string valToString(const ModelAPI_AttributeTables::Value& theVal,
242   const ModelAPI_AttributeTables::ValueType& theType) {
243   std::ostringstream aStr; // the resulting string value
244   switch(theType) {
245   case ModelAPI_AttributeTables::BOOLEAN:
246     aStr<<(theVal.myBool ? "true" : "false");
247     break;
248   case ModelAPI_AttributeTables::INTEGER:
249     aStr<<theVal.myInt;
250     break;
251   case ModelAPI_AttributeTables::DOUBLE:
252     aStr<<theVal.myDouble;
253     break;
254   case ModelAPI_AttributeTables::STRING:
255     aStr<<theVal.myStr;
256     break;
257   }
258   return aStr.str();
259 }
260
261 /// Returns true if something in selection is presented in the results list
262 static bool isInResults(AttributeSelectionListPtr theSelection,
263                         const std::list<ResultPtr>& theResults,
264                         std::set<ResultPtr>& theCashedResults)
265 {
266   // collect all results into a cashed set
267   if (theCashedResults.empty()) {
268     std::list<ResultPtr>::const_iterator aRes = theResults.cbegin();
269     for(; aRes != theResults.cend(); aRes++) {
270       if (theCashedResults.count(*aRes))
271         continue;
272       else
273         theCashedResults.insert(*aRes);
274       if ((*aRes)->groupName() == ModelAPI_ResultBody::group()) {
275         ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
276         std::list<ResultPtr> aResults;
277         ModelAPI_Tools::allSubs(aResBody, aResults, false);
278         for(std::list<ResultPtr>::iterator aR = aResults.begin(); aR != aResults.end(); aR++) {
279           theCashedResults.insert(std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aR));
280         }
281       } else if ((*aRes)->groupName() == ModelAPI_ResultPart::group()) { // all results of the part
282         ResultPartPtr aResPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
283         DocumentPtr aPartDoc = aResPart->partDoc();
284         if (!aPartDoc.get() || !aPartDoc->isOpened()) { // document is not accessible
285           return false;
286         }
287         int aBodyCount = aPartDoc->size(ModelAPI_ResultBody::group());
288         for (int aBodyIndex = 0; aBodyIndex < aBodyCount; ++aBodyIndex) {
289           ResultBodyPtr aResBody =
290             std::dynamic_pointer_cast<ModelAPI_ResultBody>(
291               aPartDoc->object(ModelAPI_ResultBody::group(), aBodyIndex));
292           if (aResBody.get()) {
293             theCashedResults.insert(aResBody);
294             std::list<ResultPtr> aResults;
295             ModelAPI_Tools::allSubs(aResBody, aResults, false);
296             for(std::list<ResultPtr>::iterator aR = aResults.begin(); aR != aResults.end(); aR++) {
297               theCashedResults.insert(std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aR));
298             }
299           }
300         }
301       }
302     }
303   }
304   // if context is in results, return true
305   for(int a = 0; a < theSelection->size(); a++) {
306     AttributeSelectionPtr anAttr = theSelection->value(a);
307     ResultPtr aContext = anAttr->context();
308     // check is it group selected for groups BOP
309     if (aContext.get() && aContext->groupName() == ModelAPI_ResultGroup::group()) {
310       // it is impossible by used results check which result is used in this group result,
311       // so check the results shapes is it in results of this document or not
312       FeaturePtr aSelFeature =
313         std::dynamic_pointer_cast<ModelAPI_Feature>(theSelection->owner());
314       if (!aSelFeature.get() || aSelFeature->results().empty())
315         continue;
316       GeomShapePtr aGroupResShape = aSelFeature->firstResult()->shape();
317
318       std::set<ResultPtr>::iterator allResultsIter = theCashedResults.begin();
319       for(; allResultsIter != theCashedResults.end(); allResultsIter++) {
320         GeomShapePtr aResultShape = (*allResultsIter)->shape();
321
322         GeomAPI_Shape::ShapeType aType =
323           GeomAPI_Shape::shapeTypeByStr(theSelection->selectionType());
324         GeomAPI_ShapeExplorer aGroupResExp(aGroupResShape, aType);
325         for(; aGroupResExp.more(); aGroupResExp.next()) {
326           if (aResultShape->isSubShape(aGroupResExp.current(), false))
327             return true; // at least one shape of the group is in the used results
328         }
329       }
330     }
331     ResultBodyPtr aSelected = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anAttr->context());
332     if (!aSelected.get()) { // try to get selected feature and all its results
333       FeaturePtr aContextFeature = anAttr->contextFeature();
334       if (aContextFeature.get() && !aContextFeature->results().empty()) {
335         const std::list<ResultPtr>& allResluts = aContextFeature->results();
336         std::list<ResultPtr>::const_iterator aResIter = allResluts.cbegin();
337         for(; aResIter != allResluts.cend(); aResIter++) {
338           if (aResIter->get() && theCashedResults.count(*aResIter))
339             return true;
340         }
341       }
342     } else if (aSelected.get() && theCashedResults.count(aSelected))
343       return true;
344   }
345   return false;
346 }
347
348 void ExchangePlugin_ExportFeature::exportSTL(const std::string& theFileName)
349 {
350   // Get shape.
351   AttributeSelectionPtr aSelection = selection(STL_OBJECT_SELECTED());
352   GeomShapePtr aShape = aSelection->value();
353   if (!aShape.get()) {
354     aShape = aSelection->context()->shape();
355   }
356
357   // Get relative value and percent flag.
358   double aValue;
359   bool anIsRelative = false;
360   bool anIsASCII = false;
361
362   if (string(STL_DEFLECTION_TYPE())->value() == STL_DEFLECTION_TYPE_RELATIVE()) {
363     aValue = real(STL_RELATIVE())->value();
364     anIsRelative = true;
365   } else {
366     aValue = real(STL_ABSOLUTE())->value();
367   }
368
369   if (string(STL_FILE_TYPE())->value() == STL_FILE_TYPE_ASCII()) {
370     anIsASCII = true;
371   }            
372   // Perform the export
373   std::string anError;
374   bool aResult = false;
375
376   aResult = STLExport(theFileName,
377                       "STL",
378                       aShape,
379                       aValue,
380                       anIsRelative, 
381                       anIsASCII,
382                       anError);
383
384   if (!aResult || !anError.empty()) {
385     setError("An error occurred while exporting " + theFileName + ": " + anError);
386     return;
387   }
388 }
389
390
391 void ExchangePlugin_ExportFeature::exportXAO(const std::string& theFileName)
392 {
393   try {
394
395   std::string anError;
396   XAO::Xao aXao;
397
398   // author
399
400   std::string anAuthor = string(ExchangePlugin_ExportFeature::XAO_AUTHOR_ID())->value();
401   aXao.setAuthor(anAuthor);
402
403   // make shape for export from all results
404   std::list<GeomShapePtr> aShapes;
405   std::list<ResultPtr> aResults;
406   std::list<DocumentPtr> aDocuments; /// documents of Parts selected and used in export
407   std::map<DocumentPtr, GeomTrsfPtr> aDocTrsf; /// translation of the part
408
409   AttributeSelectionListPtr aSelection = selectionList(XAO_SELECTION_LIST_ID());
410   bool aIsSelection = aSelection->isInitialized() && aSelection->size() > 0;
411   if (aIsSelection) { // a mode for export to geom result by result
412     for(int a = 0; a < aSelection->size(); a++) {
413       AttributeSelectionPtr anAttr = aSelection->value(a);
414       ResultPtr aBodyContext =
415         std::dynamic_pointer_cast<ModelAPI_Result>(anAttr->context());
416       if (aBodyContext.get() && !aBodyContext->isDisabled() && aBodyContext->shape().get()) {
417         aResults.push_back(aBodyContext);
418         GeomShapePtr aShape = anAttr->value();
419         if (!aShape.get())
420           aShape = aBodyContext->shape();
421         aShapes.push_back(aShape);
422         if (aBodyContext->groupName() == ModelAPI_ResultPart::group()) {
423           ResultPartPtr aResPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aBodyContext);
424           DocumentPtr aPartDoc = aResPart->partDoc();
425           if (!aPartDoc.get() || !aPartDoc->isOpened()) { // document is not accessible
426             std::string msg = "Can not export XAO for not loaded part";
427             Events_InfoMessage("ExportFeature", msg, this).send();
428             return;
429           } else {
430             aDocuments.push_back(aPartDoc);
431             aDocTrsf[aPartDoc] = aResPart->summaryTrsf();
432           }
433         }
434       }
435     }
436   } else {
437     int aBodyCount = document()->size(ModelAPI_ResultBody::group());
438     for (int aBodyIndex = 0; aBodyIndex < aBodyCount; ++aBodyIndex) {
439       ResultBodyPtr aResultBody =
440           std::dynamic_pointer_cast<ModelAPI_ResultBody>(
441               document()->object(ModelAPI_ResultBody::group(), aBodyIndex));
442       if (!aResultBody.get())
443         continue;
444       aShapes.push_back(aResultBody->shape());
445       aResults.push_back(aResultBody);
446     }
447   }
448   if (aShapes.empty()) {
449     setError("No shapes to export");
450     return;
451   }
452
453
454   GeomShapePtr aShape = (aShapes.size() == 1)
455       ? *aShapes.begin()
456       : GeomAlgoAPI_CompoundBuilder::compound(aShapes);
457
458   SetShapeToXAO(aShape, &aXao, anError);
459
460   if (!anError.empty()) {
461     setError("An error occurred while exporting " + theFileName + ": " + anError);
462     return;
463   }
464
465   // geometry name
466   std::string aGeometryName = string(ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID())->value();
467   if (aGeometryName.empty() && aResults.size() == 1) {
468     // get the name from the first result
469     ResultPtr aResultBody = *aResults.begin();
470     aGeometryName = Locale::Convert::toString(aResultBody->data()->name());
471   }
472
473   aXao.getGeometry()->setName(aGeometryName);
474
475   std::set<ResultPtr> allResultsCashed; // cash to speed up searching in all results selected
476
477   // iterate all documents used
478   if (aDocuments.empty())
479     aDocuments.push_back(document());
480   std::list<DocumentPtr>::iterator aDoc = aDocuments.begin();
481   for(; aDoc != aDocuments.end(); aDoc++) {
482     // groups
483     int aGroupCount = (*aDoc)->size(ModelAPI_ResultGroup::group());
484     for (int aGroupIndex = 0; aGroupIndex < aGroupCount; ++aGroupIndex) {
485       ResultGroupPtr aResultGroup = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(
486           (*aDoc)->object(ModelAPI_ResultGroup::group(), aGroupIndex));
487       if (!aResultGroup.get() || !aResultGroup->shape().get())
488         continue;
489
490       FeaturePtr aGroupFeature = (*aDoc)->feature(aResultGroup);
491
492       AttributeSelectionListPtr aSelectionList =
493           aGroupFeature->selectionList("group_list");
494       if (!isInResults(aSelectionList, aResults, allResultsCashed))// skip group not used in result
495         continue;
496
497       // conversion of dimension
498       std::string aSelectionType = aSelectionList->selectionType();
499       GeomAPI_Shape::ShapeType aSelType = GeomAPI_Shape::shapeTypeByStr(aSelectionType);
500       std::string aDimensionString =
501         ExchangePlugin_Tools::selectionType2xaoDimension(aSelectionType);
502       XAO::Dimension aGroupDimension = XAO::XaoUtils::stringToDimension(aDimensionString);
503
504       XAO::Group* aXaoGroup = aXao.addGroup(aGroupDimension,
505         Locale::Convert::toString(aResultGroup->data()->name()));
506
507       try {
508         GeomAPI_ShapeExplorer aGroupResExplorer(aResultGroup->shape(), aSelType);
509         for(; aGroupResExplorer.more(); aGroupResExplorer.next()) {
510           GeomShapePtr aGroupShape = aGroupResExplorer.current();
511           if (aDocTrsf.find(*aDoc) != aDocTrsf.end())
512             aGroupShape->move(aDocTrsf[*aDoc]);
513           int aReferenceID = GeomAlgoAPI_CompoundBuilder::id(aShape, aGroupShape);
514           if (aReferenceID == 0) // selected value does not found in the exported shape
515             continue;
516           std::string aReferenceString = XAO::XaoUtils::intToString(aReferenceID);
517           int anElementID =
518             aXao.getGeometry()->getElementIndexByReference(aGroupDimension, aReferenceString);
519           aXaoGroup->add(anElementID);
520         }
521       } catch (XAO::XAO_Exception& e) {
522         // LCOV_EXCL_START
523         std::string msg = "An error occurred while exporting group " +
524           Locale::Convert::toString(aResultGroup->data()->name());
525         msg += ".\n";
526         msg += e.what();
527         msg += "\n";
528         msg += "=> skipping this group from XAO export.";
529         Events_InfoMessage("ExportFeature", msg, this).send();
530         aXao.removeGroup(aXaoGroup);
531         // LCOV_EXCL_STOP
532       }
533     }
534
535     // fields
536     int aFieldCount = (*aDoc)->size(ModelAPI_ResultField::group());
537     for (int aFieldIndex = 0; aFieldIndex < aFieldCount; ++aFieldIndex) {
538       ResultFieldPtr aResultField = std::dynamic_pointer_cast<ModelAPI_ResultField>(
539         (*aDoc)->object(ModelAPI_ResultField::group(), aFieldIndex));
540
541       FeaturePtr aFieldFeature = (*aDoc)->feature(aResultField);
542
543       AttributeSelectionListPtr aSelectionList =
544           aFieldFeature->selectionList("selected");
545       std::string aSelectionType = aSelectionList->selectionType();
546       bool isWholePart = aSelectionType == "part";
547       // skip field not used in results
548       if (!isWholePart && !isInResults(aSelectionList, aResults, allResultsCashed))
549         continue;
550
551       // conversion of dimension
552       std::string aDimensionString =
553         ExchangePlugin_Tools::selectionType2xaoDimension(aSelectionType);
554       XAO::Dimension aFieldDimension = XAO::XaoUtils::stringToDimension(aDimensionString);
555       // get tables and their type
556       std::shared_ptr<ModelAPI_AttributeTables> aTables = aFieldFeature->tables("values");
557       std::string aTypeString = ExchangePlugin_Tools::valuesType2xaoType(aTables->type());
558       XAO::Type aFieldType = XAO::XaoUtils::stringToFieldType(aTypeString);
559
560       XAO::Field* aXaoField = aXao.addField(aFieldType, aFieldDimension, aTables->columns(),
561         Locale::Convert::toString(aResultField->data()->name()));
562
563
564       try {
565         // set components names
566         AttributeStringArrayPtr aComponents = aFieldFeature->stringArray("components_names");
567         for(int aComp = 0; aComp < aComponents->size(); aComp++) {
568           std::string aName = aComponents->value(aComp);
569           aXaoField->setComponentName(aComp, aName);
570         }
571
572         AttributeIntArrayPtr aStamps = aFieldFeature->intArray("stamps");
573         for (int aStepIndex = 0; aStepIndex < aTables->tables(); aStepIndex++) {
574           XAO::Step* aStep = aXaoField->addNewStep(aStepIndex + 1);
575           aStep->setStep(aStepIndex + 1);
576           int aStampIndex = aStamps->value(aStepIndex);
577           aStep->setStamp(aStampIndex);
578           int aNumElements = isWholePart ? aXaoField->countElements() : aTables->rows();
579           int aNumComps = aTables->columns();
580           std::set<int> aFilledIDs; // to fill the rest by defaults
581           // omit default values first row
582           for(int aRow = isWholePart ? 0 : 1; aRow < aNumElements; aRow++) {
583             for(int aCol = 0; aCol < aNumComps; aCol++) {
584               int anElementID = 0;
585               if (!isWholePart) {
586                 // element index actually is the ID of the selection
587                 AttributeSelectionPtr aSel = aSelectionList->value(aRow - 1);
588                 int aReferenceID = GeomAlgoAPI_CompoundBuilder::id(aShape, aSel->value());
589                 if (aReferenceID == 0) // selected value does not found in the exported shape
590                   continue;
591
592                 std::string aReferenceString = XAO::XaoUtils::intToString(aReferenceID);
593                 anElementID = aXao.getGeometry()->
594                   getElementIndexByReference(aFieldDimension, aReferenceString);
595               }
596
597               ModelAPI_AttributeTables::Value aVal = aTables->value(
598                 isWholePart ? 0 : aRow, aCol, aStepIndex);
599               std::string aStrVal = valToString(aVal, aTables->type());
600               aStep->setStringValue(isWholePart ? aRow : anElementID, aCol, aStrVal);
601               aFilledIDs.insert(anElementID);
602             }
603           }
604           if (!isWholePart) { // fill the rest values by default ones
605             XAO::GeometricElementList::iterator allElem =
606               aXao.getGeometry()->begin(aFieldDimension);
607             for(; allElem != aXao.getGeometry()->end(aFieldDimension); allElem++) {
608               if (aFilledIDs.find(allElem->first) != aFilledIDs.end())
609                 continue;
610               for(int aCol = 0; aCol < aNumComps; aCol++) {
611                 // default value
612                 ModelAPI_AttributeTables::Value aVal = aTables->value(0, aCol, aStepIndex);
613                 std::string aStrVal = valToString(aVal, aTables->type());
614                 aStep->setStringValue(allElem->first, aCol, aStrVal);
615               }
616             }
617           }
618         }
619       } catch (XAO::XAO_Exception& e) {
620         // LCOV_EXCL_START
621         std::string msg = "An error occurred while exporting field " +
622           Locale::Convert::toString(aResultField->data()->name());
623         msg += ".\n";
624         msg += e.what();
625         msg += "\n";
626         msg += "=> skipping this field from XAO export.";
627         Events_InfoMessage("ExportFeature", msg, this).send();
628         aXao.removeField(aXaoField);
629         // LCOV_EXCL_STOP
630       }
631     }
632   }
633
634   // exporting
635   XAOExport(theFileName, &aXao, anError);
636
637   if (!anError.empty()) {
638     setError("An error occurred while exporting " + theFileName + ": " + anError);
639     return;
640   }
641
642 // LCOV_EXCL_START
643   } catch (XAO::XAO_Exception& e) {
644     std::string anError = e.what();
645     setError("An error occurred while exporting " + theFileName + ": " + anError);
646     return;
647   }
648 // LCOV_EXCL_STOP
649 }
650
651 bool ExchangePlugin_ExportFeature::isMacro() const
652 {
653   if (!data().get() || !data()->isValid())
654     return false;
655   ExchangePlugin_ExportFeature* aThis = ((ExchangePlugin_ExportFeature*)(this));
656   AttributeStringPtr aFormatAttr = aThis->string(FILE_FORMAT_ID());
657   std::string aFormat(aFormatAttr.get() ? aFormatAttr->value() : "");
658
659   if (aFormat.empty()) { // get default format for the extension
660     AttributeStringPtr aFilePathAttr = aThis->string(FILE_PATH_ID());
661     std::string aFilePath = aFilePathAttr->value();
662     if (!aFilePath.empty()) {
663       std::string anExtension = GeomAlgoAPI_Tools::File_Tools::extension(aFilePath);
664       aFormat = anExtension;
665     }
666   }
667
668   if (aFormat == "XAO") { // on export to GEOM the selection attribute is filled - this is
669                           // an exceptional case where export to XAO feature must be kept
670     AttributeSelectionListPtr aList = aThis->selectionList(XAO_SELECTION_LIST_ID());
671     return !aList->isInitialized() || aList->size() == 0;
672   }
673   return true;
674 }