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