Salome HOME
Fix coding style.
[modules/shaper.git] / src / ExchangePlugin / ExchangePlugin_ImportFeature.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    ExchangePlugin_ImportFeature.cpp
4 // Created: Aug 28, 2014
5 // Authors:  Sergey BELASH, Sergey POKHODENKO
6
7 #include <ExchangePlugin_ImportFeature.h>
8
9 #include <algorithm>
10 #include <string>
11
12 #include <Config_Common.h>
13 #include <Config_PropManager.h>
14
15 #include <GeomAlgoAPI_BREPImport.h>
16 #include <GeomAlgoAPI_IGESImport.h>
17 #include <GeomAlgoAPI_STEPImport.h>
18 #include <GeomAlgoAPI_Tools.h>
19 #include <GeomAlgoAPI_XAOImport.h>
20
21 #include <GeomAPI_Shape.h>
22 #include <GeomAPI_ShapeExplorer.h>
23
24 #include <ModelAPI_AttributeRefList.h>
25 #include <ModelAPI_AttributeSelectionList.h>
26 #include <ModelAPI_AttributeString.h>
27 #include <ModelAPI_AttributeStringArray.h>
28 #include <ModelAPI_AttributeIntArray.h>
29 #include <ModelAPI_AttributeTables.h>
30 #include <ModelAPI_BodyBuilder.h>
31 #include <ModelAPI_Data.h>
32 #include <ModelAPI_Document.h>
33 #include <ModelAPI_Events.h>
34 #include <ModelAPI_Object.h>
35 #include <ModelAPI_ResultBody.h>
36 #include <ModelAPI_ResultGroup.h>
37 #include <ModelAPI_Session.h>
38 #include <ModelAPI_Validator.h>
39
40 #include <XAO_Xao.hxx>
41 #include <XAO_Group.hxx>
42 #include <XAO_Field.hxx>
43 #include <XAO_Step.hxx>
44
45 #include <ExchangePlugin_Tools.h>
46
47 ExchangePlugin_ImportFeature::ExchangePlugin_ImportFeature()
48 {
49 }
50
51 ExchangePlugin_ImportFeature::~ExchangePlugin_ImportFeature()
52 {
53   // TODO Auto-generated destructor stub
54 }
55
56 /*
57  * Request for initialization of data model of the feature: adding all attributes
58  */
59 void ExchangePlugin_ImportFeature::initAttributes()
60 {
61   data()->addAttribute(ExchangePlugin_ImportFeature::FILE_PATH_ID(),
62                        ModelAPI_AttributeString::typeId());
63   AttributePtr aFeaturesAttribute =
64     data()->addAttribute(ExchangePlugin_ImportFeature::FEATURES_ID(),
65                          ModelAPI_AttributeRefList::typeId());
66   aFeaturesAttribute->setIsArgument(false);
67
68   ModelAPI_Session::get()->validators()->registerNotObligatory(
69       getKind(), ExchangePlugin_ImportFeature::FEATURES_ID());
70 }
71
72 /*
73  * Computes or recomputes the results
74  */
75 void ExchangePlugin_ImportFeature::execute()
76 {
77   AttributeStringPtr aFilePathAttr = string(ExchangePlugin_ImportFeature::FILE_PATH_ID());
78   std::string aFilePath = aFilePathAttr->value();
79   if (aFilePath.empty()) {
80     setError("File path is empty.");
81     return;
82   }
83
84   importFile(aFilePath);
85 }
86
87 std::shared_ptr<ModelAPI_ResultBody> ExchangePlugin_ImportFeature::createResultBody(
88     std::shared_ptr<GeomAPI_Shape> aGeomShape)
89 {
90   std::shared_ptr<ModelAPI_ResultBody> aResultBody = document()->createBody(data());
91   //LoadNamingDS of the imported shape
92   loadNamingDS(aGeomShape, aResultBody);
93   return aResultBody;
94 }
95
96 void ExchangePlugin_ImportFeature::importFile(const std::string& theFileName)
97 {
98   // "*.brep" -> "BREP"
99   std::string anExtension = GeomAlgoAPI_Tools::File_Tools::extension(theFileName);
100
101   if (anExtension == "XAO") {
102     importXAO(theFileName);
103     return;
104   }
105
106   // Perform the import
107   std::string anError;
108   std::shared_ptr<GeomAPI_Shape> aGeomShape;
109   if (anExtension == "BREP" || anExtension == "BRP") {
110     aGeomShape = BREPImport(theFileName, anExtension, anError);
111   } else if (anExtension == "STEP" || anExtension == "STP") {
112     aGeomShape = STEPImport(theFileName, anExtension, anError);
113   } else if (anExtension == "IGES" || anExtension == "IGS") {
114     aGeomShape = IGESImport(theFileName, anExtension, anError);
115   } else {
116     anError = "Unsupported format: " + anExtension;
117   }
118
119   // Check if shape is valid
120   if (!anError.empty()) {
121     setError("An error occurred while importing " + theFileName + ": " + anError);
122     return;
123   }
124
125   // Pass the results into the model
126   std::string anObjectName = GeomAlgoAPI_Tools::File_Tools::name(theFileName);
127   data()->setName(anObjectName);
128
129   setResult(createResultBody(aGeomShape));
130 }
131
132 void ExchangePlugin_ImportFeature::importXAO(const std::string& theFileName)
133 {
134   try {
135   std::string anError;
136
137   XAO::Xao aXao;
138   std::shared_ptr<GeomAPI_Shape> aGeomShape = XAOImport(theFileName, anError, &aXao);
139
140   if (!anError.empty()) {
141     setError("An error occurred while importing " + theFileName + ": " + anError);
142     return;
143   }
144
145   XAO::Geometry* aXaoGeometry = aXao.getGeometry();
146
147   // use the geometry name or the file name for the feature
148   std::string aBodyName = aXaoGeometry->getName();
149   if (aBodyName.empty())
150     aBodyName = GeomAlgoAPI_Tools::File_Tools::name(theFileName);
151   data()->setName(aBodyName);
152
153   ResultBodyPtr aResultBody = createResultBody(aGeomShape);
154   setResult(aResultBody);
155
156   // Process groups/fields
157   std::shared_ptr<ModelAPI_AttributeRefList> aRefListOfGroups =
158       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(data()->attribute(FEATURES_ID()));
159
160   // Remove previous groups/fields stored in RefList
161   std::list<ObjectPtr> anGroupList = aRefListOfGroups->list();
162   std::list<ObjectPtr>::iterator anGroupIt = anGroupList.begin();
163   for (; anGroupIt != anGroupList.end(); ++anGroupIt) {
164     std::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_Feature::feature(*anGroupIt);
165     if (aFeature)
166       document()->removeFeature(aFeature);
167   }
168
169   // Create new groups
170   for (int aGroupIndex = 0; aGroupIndex < aXao.countGroups(); ++aGroupIndex) {
171     XAO::Group* aXaoGroup = aXao.getGroup(aGroupIndex);
172
173     std::shared_ptr<ModelAPI_Feature> aGroupFeature = addFeature("Group");
174
175     // group name
176     if (!aXaoGroup->getName().empty())
177       aGroupFeature->data()->setName(aXaoGroup->getName());
178
179     // fill selection
180     AttributeSelectionListPtr aSelectionList = aGroupFeature->selectionList("group_list");
181
182     // conversion of dimension
183     std::string aDimensionString = XAO::XaoUtils::dimensionToString(aXaoGroup->getDimension());
184     std::string aSelectionType =
185       ExchangePlugin_Tools::xaoDimension2selectionType(aDimensionString);
186
187     aSelectionList->setSelectionType(aSelectionType);
188     for (int anElementIndex = 0; anElementIndex < aXaoGroup->count(); ++anElementIndex) {
189       aSelectionList->append(aResultBody, GeomShapePtr());
190       // complex conversion of element index to reference id
191       int anElementID = aXaoGroup->get(anElementIndex);
192       std::string aReferenceString =
193           aXaoGeometry->getElementReference(aXaoGroup->getDimension(), anElementID);
194       int aReferenceID = XAO::XaoUtils::stringToInt(aReferenceString);
195
196       aSelectionList->value(anElementIndex)->setId(aReferenceID);
197     }
198   }
199   // Create new fields
200   for (int aFieldIndex = 0; aFieldIndex < aXao.countFields(); ++aFieldIndex) {
201     XAO::Field* aXaoField = aXao.getField(aFieldIndex);
202
203     std::shared_ptr<ModelAPI_Feature> aFieldFeature = addFeature("Field");
204
205     // group name
206     if (!aXaoField->getName().empty())
207       aFieldFeature->data()->setName(aXaoField->getName());
208
209     // fill selection
210     AttributeSelectionListPtr aSelectionList = aFieldFeature->selectionList("selected");
211
212     // conversion of dimension
213     std::string aDimensionString = XAO::XaoUtils::dimensionToString(aXaoField->getDimension());
214     std::string aSelectionType =
215       ExchangePlugin_Tools::xaoDimension2selectionType(aDimensionString);
216     aSelectionList->setSelectionType(aSelectionType);
217     // limitation: now in XAO fields are related to everything, so, iterate all sub-shapes to fill
218     int aCountSelected = aXaoField->countElements();
219     int aResults = document()->size(ModelAPI_ResultBody::group());
220     for(int a = 0; a < aResults && aCountSelected; a++) {
221       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(
222         document()->object(ModelAPI_ResultBody::group(), a));
223       if (!aBody.get())
224         continue;
225       // check that only results that were created before this field are used
226       FeaturePtr aResultFeature = document()->feature(aBody);
227       if (!aResultFeature.get())
228         continue;
229       GeomShapePtr aShape = aBody->shape();
230       if (!aShape.get() || aShape->isNull())
231         continue;
232       GeomAPI_ShapeExplorer anExp(aShape, GeomAPI_Shape::shapeTypeByStr(aSelectionType));
233       for(; anExp.more(); anExp.next()) {
234         aSelectionList->append(aBody, anExp.current());
235         aCountSelected--;
236         if (aCountSelected == 0)
237           break;
238       }
239     }
240
241     // conversion of type
242     XAO::Type aFieldType = aXaoField->getType();
243     std::string aTypeString = XAO::XaoUtils::fieldTypeToString(aFieldType);
244     ModelAPI_AttributeTables::ValueType aType =
245       ExchangePlugin_Tools::xaoType2valuesType(aTypeString);
246     // set components names
247     AttributeStringArrayPtr aComponents = aFieldFeature->stringArray("components_names");
248     aComponents->setSize(aXaoField->countComponents());
249     for(int aComp = 0; aComp < aXaoField->countComponents(); aComp++) {
250       aComponents->setValue(aComp, aXaoField->getComponentName(aComp));
251     }
252
253     AttributeIntArrayPtr aStamps = aFieldFeature->intArray("stamps");
254     aStamps->setSize(aXaoField->countSteps());
255     std::shared_ptr<ModelAPI_AttributeTables> aTables = aFieldFeature->tables("values");
256     aTables->setSize(
257       aXaoField->countElements() + 1, aXaoField->countComponents(), aXaoField->countSteps());
258     aTables->setType(aType);
259     // iterate steps
260     XAO::stepIterator aStepIter = aXaoField->begin();
261     for(int aStepIndex = 0; aStepIter != aXaoField->end(); aStepIter++, aStepIndex++) {
262       aStamps->setValue(aStepIndex, (*aStepIter)->getStamp());
263       for(int aRow = 1; aRow <= aXaoField->countElements(); aRow++) {
264         for(int aCol = 0; aCol < aXaoField->countComponents(); aCol++) {
265           ModelAPI_AttributeTables::Value aVal;
266           std::string aValStr = (*aStepIter)->getStringValue(aRow - 1, aCol);
267           switch(aType) {
268           case ModelAPI_AttributeTables::BOOLEAN:
269             aVal.myBool = aValStr == "True";
270             break;
271           case ModelAPI_AttributeTables::INTEGER:
272             aVal.myInt = atoi(aValStr.c_str());
273             break;
274           case ModelAPI_AttributeTables::DOUBLE:
275             aVal.myDouble = atof(aValStr.c_str());
276             break;
277           case ModelAPI_AttributeTables::STRING:
278             aVal.myStr = aValStr;
279             break;
280           }
281           aTables->setValue(aVal, aRow, aCol, aStepIndex);
282         }
283       }
284     }
285   }
286   // Top avoid problems in Object Browser update: issue #1647.
287   ModelAPI_EventCreator::get()->sendReordered(
288     std::dynamic_pointer_cast<ModelAPI_Feature>(aRefListOfGroups->owner()));
289
290   } catch (XAO::XAO_Exception& e) {
291     std::string anError = e.what();
292     setError("An error occurred while importing " + theFileName + ": " + anError);
293     return;
294   }
295 }
296
297 //============================================================================
298 std::shared_ptr<ModelAPI_Feature> ExchangePlugin_ImportFeature::addFeature(
299     std::string theID)
300 {
301   std::shared_ptr<ModelAPI_Feature> aNew = document()->addFeature(theID, false);
302   if (aNew)
303     data()->reflist(FEATURES_ID())->append(aNew);
304   // set as current also after it becomes sub to set correctly enabled for other subs
305   //document()->setCurrentFeature(aNew, false);
306   return aNew;
307 }
308
309 void ExchangePlugin_ImportFeature::removeFeature(
310     std::shared_ptr<ModelAPI_Feature> theFeature)
311 {
312   if (!data()->isValid())
313     return;
314   AttributeRefListPtr aList = reflist(FEATURES_ID());
315   aList->remove(theFeature);
316 }
317
318 int ExchangePlugin_ImportFeature::numberOfSubs(bool forTree) const
319 {
320   return data()->reflist(FEATURES_ID())->size(true);
321 }
322
323 std::shared_ptr<ModelAPI_Feature> ExchangePlugin_ImportFeature::subFeature(
324     const int theIndex, bool forTree)
325 {
326   ObjectPtr anObj = data()->reflist(FEATURES_ID())->object(theIndex, false);
327   FeaturePtr aRes = std::dynamic_pointer_cast<ModelAPI_Feature>(anObj);
328   return aRes;
329 }
330
331 int ExchangePlugin_ImportFeature::subFeatureId(const int theIndex) const
332 {
333   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
334       ModelAPI_AttributeRefList>(data()->attribute(FEATURES_ID()));
335   std::list<ObjectPtr> aFeatures = aRefList->list();
336   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin();
337   int aResultIndex = 1; // number of the counted (created) features, started from 1
338   int aFeatureIndex = -1; // number of the not-empty features in the list
339   for (; anIt != aFeatures.end(); anIt++) {
340     if (anIt->get())
341       aFeatureIndex++;
342     if (aFeatureIndex == theIndex)
343       break;
344     aResultIndex++;
345   }
346   return aResultIndex;
347 }
348
349 bool ExchangePlugin_ImportFeature::isSub(ObjectPtr theObject) const
350 {
351   // check is this feature of result
352   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
353   if (aFeature)
354     return data()->reflist(FEATURES_ID())->isInList(aFeature);
355   return false;
356 }
357
358 //============================================================================
359 void ExchangePlugin_ImportFeature::loadNamingDS(
360     std::shared_ptr<GeomAPI_Shape> theGeomShape,
361     std::shared_ptr<ModelAPI_ResultBody> theResultBody)
362 {
363   //load result
364   theResultBody->store(theGeomShape);
365
366   int aTag(1);
367   std::string aNameMS = "Shape";
368   theResultBody->loadFirstLevel(theGeomShape, aNameMS, aTag);
369 }