]> SALOME platform Git repositories - modules/shaper.git/blob - src/ExchangePlugin/ExchangePlugin_ExportFeature.cpp
Salome HOME
a3e92eb67e8d27330482fa2b29aeeab7c49b24fc
[modules/shaper.git] / src / ExchangePlugin / ExchangePlugin_ExportFeature.cpp
1 // Copyright (C) 2014-2019  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 #include <Config_Common.h>
31 #include <Config_PropManager.h>
32
33 #include <GeomAlgoAPI_BREPExport.h>
34 #include <GeomAlgoAPI_CompoundBuilder.h>
35 #include <GeomAlgoAPI_IGESExport.h>
36 #include <GeomAlgoAPI_STEPExport.h>
37 #include <GeomAlgoAPI_Tools.h>
38 #include <GeomAlgoAPI_XAOExport.h>
39
40 #include <GeomAPI_Shape.h>
41
42 #include <ModelAPI_AttributeSelectionList.h>
43 #include <ModelAPI_AttributeString.h>
44 #include <ModelAPI_AttributeStringArray.h>
45 #include <ModelAPI_AttributeIntArray.h>
46 #include <ModelAPI_AttributeTables.h>
47 #include <ModelAPI_Data.h>
48 #include <ModelAPI_Document.h>
49 #include <ModelAPI_Object.h>
50 #include <ModelAPI_ResultBody.h>
51 #include <ModelAPI_ResultGroup.h>
52 #include <ModelAPI_ResultField.h>
53 #include <ModelAPI_Session.h>
54 #include <ModelAPI_Validator.h>
55 #include <ModelAPI_Tools.h>
56
57 #include <Events_InfoMessage.h>
58
59 #include <XAO_Group.hxx>
60 #include <XAO_Field.hxx>
61 #include <XAO_Xao.hxx>
62 #include <XAO_Geometry.hxx>
63
64 #include <ExchangePlugin_Tools.h>
65
66 ExchangePlugin_ExportFeature::ExchangePlugin_ExportFeature()
67 {
68 }
69
70 ExchangePlugin_ExportFeature::~ExchangePlugin_ExportFeature()
71 {
72   // TODO Auto-generated destructor stub
73 }
74
75 /*
76  * Request for initialization of data model of the feature: adding all attributes
77  */
78 void ExchangePlugin_ExportFeature::initAttributes()
79 {
80   data()->addAttribute(ExchangePlugin_ExportFeature::EXPORT_TYPE_ID(),
81     ModelAPI_AttributeString::typeId());
82   data()->addAttribute(ExchangePlugin_ExportFeature::FILE_PATH_ID(),
83     ModelAPI_AttributeString::typeId());
84   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID(),
85     ModelAPI_AttributeString::typeId());
86   data()->addAttribute(ExchangePlugin_ExportFeature::FILE_FORMAT_ID(),
87     ModelAPI_AttributeString::typeId());
88   data()->addAttribute(ExchangePlugin_ExportFeature::SELECTION_LIST_ID(),
89     ModelAPI_AttributeSelectionList::typeId());
90   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_AUTHOR_ID(),
91     ModelAPI_AttributeString::typeId());
92   data()->addAttribute(ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID(),
93     ModelAPI_AttributeString::typeId());
94
95   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
96     ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID());
97   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
98     ExchangePlugin_ExportFeature::XAO_AUTHOR_ID());
99   ModelAPI_Session::get()->validators()->registerNotObligatory(getKind(),
100     ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID());
101 }
102
103 void ExchangePlugin_ExportFeature::attributeChanged(const std::string& theID)
104 {
105   if (theID == XAO_FILE_PATH_ID()) {
106     string(ExchangePlugin_ExportFeature::FILE_PATH_ID())->setValue(
107       string(ExchangePlugin_ExportFeature::XAO_FILE_PATH_ID())->value());
108   }
109 }
110
111 /*
112  * Computes or recomputes the results
113  */
114 void ExchangePlugin_ExportFeature::execute()
115 {
116   AttributeStringPtr aFormatAttr =
117       this->string(ExchangePlugin_ExportFeature::FILE_FORMAT_ID());
118   std::string aFormat = aFormatAttr->value();
119
120   AttributeStringPtr aFilePathAttr =
121       this->string(ExchangePlugin_ExportFeature::FILE_PATH_ID());
122   std::string aFilePath = aFilePathAttr->value();
123   if (aFilePath.empty())
124     return;
125
126   exportFile(aFilePath, aFormat);
127 }
128
129 void ExchangePlugin_ExportFeature::exportFile(const std::string& theFileName,
130                                               const std::string& theFormat)
131 {
132   std::string aFormatName = theFormat;
133
134   if (aFormatName.empty()) { // get default format for the extension
135     // ".brep" -> "BREP"
136     std::string anExtension = GeomAlgoAPI_Tools::File_Tools::extension(theFileName);
137     if (anExtension == "BREP" || anExtension == "BRP") {
138       aFormatName = "BREP";
139     } else if (anExtension == "STEP" || anExtension == "STP") {
140       aFormatName = "STEP";
141     } else if (anExtension == "IGES" || anExtension == "IGS") {
142       aFormatName = "IGES-5.1";
143     } else if (anExtension == "XAO") {
144       aFormatName = "XAO";
145     } else {
146       aFormatName = anExtension;
147     }
148   }
149
150   if (aFormatName == "XAO") {
151     exportXAO(theFileName);
152     return;
153   }
154
155   // make shape for export from selected shapes
156   AttributeSelectionListPtr aSelectionListAttr =
157       this->selectionList(ExchangePlugin_ExportFeature::SELECTION_LIST_ID());
158   std::list<GeomShapePtr> aShapes;
159   for (int i = 0, aSize = aSelectionListAttr->size(); i < aSize; ++i) {
160     AttributeSelectionPtr anAttrSelection = aSelectionListAttr->value(i);
161     std::shared_ptr<GeomAPI_Shape> aCurShape = anAttrSelection->value();
162     if (aCurShape.get() == NULL)
163       aCurShape = anAttrSelection->context()->shape();
164     if (aCurShape.get() != NULL)
165       aShapes.push_back(aCurShape);
166   }
167
168   // Store compound if we have more than one shape.
169   std::shared_ptr<GeomAPI_Shape> aShape;
170   if(aShapes.size() == 1) {
171     aShape = aShapes.front();
172   } else {
173     aShape = GeomAlgoAPI_CompoundBuilder::compound(aShapes);
174   }
175
176   // Perform the export
177   std::string anError;
178   bool aResult = false;
179   if (aFormatName == "BREP") {
180     aResult = BREPExport(theFileName, aFormatName, aShape, anError);
181   } else if (aFormatName == "STEP") {
182     aResult = STEPExport(theFileName, aFormatName, aShape, anError);
183   } else if (aFormatName.substr(0, 4) == "IGES") {
184     aResult = IGESExport(theFileName, aFormatName, aShape, anError);
185   } else {
186     anError = "Unsupported format: " + aFormatName;
187   }
188
189   if (!anError.empty()) {
190     setError("An error occurred while exporting " + theFileName + ": " + anError);
191     return;
192   }
193 }
194
195 /// Returns XAO string by the value from the table
196 static std::string valToString(const ModelAPI_AttributeTables::Value& theVal,
197   const ModelAPI_AttributeTables::ValueType& theType) {
198   std::ostringstream aStr; // the resulting string value
199   switch(theType) {
200   case ModelAPI_AttributeTables::BOOLEAN:
201     aStr<<(theVal.myBool ? "true" : "false");
202     break;
203   case ModelAPI_AttributeTables::INTEGER:
204     aStr<<theVal.myInt;
205     break;
206   case ModelAPI_AttributeTables::DOUBLE:
207     aStr<<theVal.myDouble;
208     break;
209   case ModelAPI_AttributeTables::STRING:
210     aStr<<theVal.myStr;
211     break;
212   }
213   return aStr.str();
214 }
215
216 /// Returns true if something in selection is presented in the results list
217 static bool isInResults(AttributeSelectionListPtr theSelection,
218                         const std::list<ResultBodyPtr>& theResults,
219                         std::set<ResultBodyPtr>& theCashedResults)
220 {
221   // collect all results into a cashed set
222   if (theCashedResults.empty()) {
223     std::list<ResultPtr> aResults;
224     std::list<ResultBodyPtr>::const_iterator aRes = theResults.cbegin();
225     for(; aRes != theResults.cend(); aRes++) {
226       if (theCashedResults.count(*aRes))
227         continue;
228       else
229         theCashedResults.insert(*aRes);
230       std::list<ResultPtr> aResults;
231       ModelAPI_Tools::allSubs(*aRes, aResults, false);
232       for(std::list<ResultPtr>::iterator aR = aResults.begin(); aR != aResults.end(); aR++) {
233         theCashedResults.insert(std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aR));
234       }
235     }
236   }
237   // if context is in results, return true
238   for(int a = 0; a < theSelection->size(); a++) {
239     AttributeSelectionPtr anAttr = theSelection->value(a);
240     ResultBodyPtr aSelected= std::dynamic_pointer_cast<ModelAPI_ResultBody>(anAttr->context());
241     if (aSelected.get() && theCashedResults.count(aSelected))
242       return true;
243   }
244   return false;
245 }
246
247 void ExchangePlugin_ExportFeature::exportXAO(const std::string& theFileName)
248 {
249   try {
250
251   std::string anError;
252   XAO::Xao aXao;
253
254   // author
255
256   std::string anAuthor = string(ExchangePlugin_ExportFeature::XAO_AUTHOR_ID())->value();
257   aXao.setAuthor(anAuthor);
258
259   // make shape for export from all results
260   std::list<GeomShapePtr> aShapes;
261   std::list<ResultBodyPtr> aResults;
262
263   AttributeSelectionListPtr aSelection = selectionList(SELECTION_LIST_ID());
264   bool aIsSelection = aSelection->isInitialized() && aSelection->size() > 0;
265   if (aIsSelection) { // a mode for export to geom result by result
266     for(int a = 0; a < aSelection->size(); a++) {
267       AttributeSelectionPtr anAttr = aSelection->value(a);
268       ResultBodyPtr aBodyContext =
269         std::dynamic_pointer_cast<ModelAPI_ResultBody>(anAttr->context());
270       if (aBodyContext.get() && !aBodyContext->isDisabled() && aBodyContext->shape().get()) {
271         aResults.push_back(aBodyContext);
272         GeomShapePtr aShape = anAttr->value();
273         if (!aShape.get())
274           aShape = aBodyContext->shape();
275         aShapes.push_back(aShape);
276       }
277     }
278   } else {
279     int aBodyCount = document()->size(ModelAPI_ResultBody::group());
280     for (int aBodyIndex = 0; aBodyIndex < aBodyCount; ++aBodyIndex) {
281       ResultBodyPtr aResultBody =
282           std::dynamic_pointer_cast<ModelAPI_ResultBody>(
283               document()->object(ModelAPI_ResultBody::group(), aBodyIndex));
284       if (!aResultBody.get())
285         continue;
286       aShapes.push_back(aResultBody->shape());
287       aResults.push_back(aResultBody);
288     }
289   }
290   if (aShapes.empty()) {
291     setError("No shapes to export");
292     return;
293   }
294
295
296   GeomShapePtr aShape = (aShapes.size() == 1)
297       ? *aShapes.begin()
298       : GeomAlgoAPI_CompoundBuilder::compound(aShapes);
299
300   SetShapeToXAO(aShape, &aXao, anError);
301
302   if (!anError.empty()) {
303     setError("An error occurred while exporting " + theFileName + ": " + anError);
304     return;
305   }
306
307   // geometry name
308   std::string aGeometryName = string(ExchangePlugin_ExportFeature::XAO_GEOMETRY_NAME_ID())->value();
309   if (aGeometryName.empty() && aResults.size() == 1) {
310     // get the name from the first result
311     ResultBodyPtr aResultBody = *aResults.begin();
312     aGeometryName = aResultBody->data()->name();
313   }
314
315   aXao.getGeometry()->setName(aGeometryName);
316
317   std::set<ResultBodyPtr> allResultsCashed; // cash to speed up searching in all results selected
318
319   // groups
320   int aGroupCount = document()->size(ModelAPI_ResultGroup::group());
321   for (int aGroupIndex = 0; aGroupIndex < aGroupCount; ++aGroupIndex) {
322     ResultGroupPtr aResultGroup =
323         std::dynamic_pointer_cast<ModelAPI_ResultGroup>(
324             document()->object(ModelAPI_ResultGroup::group(), aGroupIndex));
325
326     FeaturePtr aGroupFeature = document()->feature(aResultGroup);
327
328     AttributeSelectionListPtr aSelectionList =
329         aGroupFeature->selectionList("group_list");
330
331     if (!isInResults(aSelectionList, aResults, allResultsCashed))// skip group not used in results
332       continue;
333
334     // conversion of dimension
335     std::string aSelectionType = aSelectionList->selectionType();
336     std::string aDimensionString =
337       ExchangePlugin_Tools::selectionType2xaoDimension(aSelectionType);
338     XAO::Dimension aGroupDimension = XAO::XaoUtils::stringToDimension(aDimensionString);
339
340     XAO::Group* aXaoGroup = aXao.addGroup(aGroupDimension,
341                                           aResultGroup->data()->name());
342
343     try {
344       for (int aSelectionIndex = 0; aSelectionIndex < aSelectionList->size(); ++aSelectionIndex) {
345         AttributeSelectionPtr aSelection = aSelectionList->value(aSelectionIndex);
346
347         // complex conversion of reference id to element index
348         // gives bad id in case the selection is done from python script
349         // => using GeomAlgoAPI_CompoundBuilder::id instead
350         // int aReferenceID_old = aSelection->Id();
351
352         int aReferenceID = GeomAlgoAPI_CompoundBuilder::id(aShape, aSelection->value());
353
354         if (aReferenceID == 0) // selected value does not found in the exported shape
355           continue;
356
357         std::string aReferenceString = XAO::XaoUtils::intToString(aReferenceID);
358         int anElementID =
359           aXao.getGeometry()->getElementIndexByReference(aGroupDimension, aReferenceString);
360
361         aXaoGroup->add(anElementID);
362       }
363     } catch (XAO::XAO_Exception& e) {
364       std::string msg = "An error occurred while exporting group " + aResultGroup->data()->name();
365       msg += ".\n";
366       msg += e.what();
367       msg += "\n";
368       msg += "=> skipping this group from XAO export.";
369       Events_InfoMessage("ExportFeature", msg, this).send();
370       aXao.removeGroup(aXaoGroup);
371     }
372   }
373
374   // fields
375   int aFieldCount = document()->size(ModelAPI_ResultField::group());
376   for (int aFieldIndex = 0; aFieldIndex < aFieldCount; ++aFieldIndex) {
377     ResultFieldPtr aResultField =
378         std::dynamic_pointer_cast<ModelAPI_ResultField>(
379             document()->object(ModelAPI_ResultField::group(), aFieldIndex));
380
381     FeaturePtr aFieldFeature = document()->feature(aResultField);
382
383     AttributeSelectionListPtr aSelectionList =
384         aFieldFeature->selectionList("selected");
385     std::string aSelectionType = aSelectionList->selectionType();
386     bool isWholePart = aSelectionType == "part";
387
388     if (!isWholePart &&
389         !isInResults(aSelectionList, aResults, allResultsCashed))// skip field not used in results
390       continue;
391
392     // conversion of dimension
393     std::string aDimensionString =
394       ExchangePlugin_Tools::selectionType2xaoDimension(aSelectionType);
395     XAO::Dimension aFieldDimension = XAO::XaoUtils::stringToDimension(aDimensionString);
396     // get tables and their type
397     std::shared_ptr<ModelAPI_AttributeTables> aTables = aFieldFeature->tables("values");
398     std::string aTypeString = ExchangePlugin_Tools::valuesType2xaoType(aTables->type());
399     XAO::Type aFieldType = XAO::XaoUtils::stringToFieldType(aTypeString);
400
401     XAO::Field* aXaoField = aXao.addField(aFieldType, aFieldDimension, aTables->columns(),
402                                           aResultField->data()->name());
403
404
405     try {
406       // set components names
407       AttributeStringArrayPtr aComponents = aFieldFeature->stringArray("components_names");
408       for(int aComp = 0; aComp < aComponents->size(); aComp++) {
409         std::string aName = aComponents->value(aComp);
410         aXaoField->setComponentName(aComp, aName);
411       }
412
413       AttributeIntArrayPtr aStamps = aFieldFeature->intArray("stamps");
414       for (int aStepIndex = 0; aStepIndex < aTables->tables(); aStepIndex++) {
415         XAO::Step* aStep = aXaoField->addNewStep(aStepIndex);
416         aStep->setStep(aStepIndex);
417         int aStampIndex = aStamps->value(aStepIndex);
418         aStep->setStamp(aStampIndex);
419         int aNumElements = isWholePart ? aXaoField->countElements() : aTables->rows();
420         int aNumComps = aTables->columns();
421         std::set<int> aFilledIDs; // to fill the rest by defaults
422         // omit default values first row
423         for(int aRow = isWholePart ? 0 : 1; aRow < aNumElements; aRow++) {
424           for(int aCol = 0; aCol < aNumComps; aCol++) {
425             int anElementID = 0;
426             if (!isWholePart) {
427               // element index actually is the ID of the selection
428               AttributeSelectionPtr aSelection = aSelectionList->value(aRow - 1);
429               int aReferenceID = GeomAlgoAPI_CompoundBuilder::id(aShape, aSelection->value());
430               if (aReferenceID == 0) // selected value does not found in the exported shape
431                 continue;
432
433               std::string aReferenceString = XAO::XaoUtils::intToString(aReferenceID);
434               anElementID =
435                 aXao.getGeometry()->getElementIndexByReference(aFieldDimension, aReferenceString);
436             }
437
438             ModelAPI_AttributeTables::Value aVal = aTables->value(
439               isWholePart ? 0 : aRow, aCol, aStepIndex);
440             std::string aStrVal = valToString(aVal, aTables->type());
441             aStep->setStringValue(isWholePart ? aRow : anElementID, aCol, aStrVal);
442             aFilledIDs.insert(anElementID);
443           }
444         }
445         if (!isWholePart) { // fill the rest values by default ones
446           XAO::GeometricElementList::iterator allElem = aXao.getGeometry()->begin(aFieldDimension);
447           for(; allElem != aXao.getGeometry()->end(aFieldDimension); allElem++) {
448             if (aFilledIDs.find(allElem->first) != aFilledIDs.end())
449               continue;
450             for(int aCol = 0; aCol < aNumComps; aCol++) {
451               ModelAPI_AttributeTables::Value aVal = aTables->value(0, aCol, aStepIndex); // default
452               std::string aStrVal = valToString(aVal, aTables->type());
453               aStep->setStringValue(allElem->first, aCol, aStrVal);
454             }
455           }
456         }
457       }
458     } catch (XAO::XAO_Exception& e) {
459       std::string msg = "An error occurred while exporting field " + aResultField->data()->name();
460       msg += ".\n";
461       msg += e.what();
462       msg += "\n";
463       msg += "=> skipping this field from XAO export.";
464       Events_InfoMessage("ExportFeature", msg, this).send();
465       aXao.removeField(aXaoField);
466     }
467   }
468
469   // exporting
470   XAOExport(theFileName, &aXao, anError);
471
472   if (!anError.empty()) {
473     setError("An error occurred while exporting " + theFileName + ": " + anError);
474     return;
475   }
476
477 // LCOV_EXCL_START
478   } catch (XAO::XAO_Exception& e) {
479     std::string anError = e.what();
480     setError("An error occurred while exporting " + theFileName + ": " + anError);
481     return;
482   }
483 // LCOV_EXCL_STOP
484 }