]> SALOME platform Git repositories - modules/shaper.git/blob - src/ExchangePlugin/ExchangePlugin_ImportFeature.cpp
Salome HOME
Improve Model package coverage: remove unused methods, open/save tests improvements
[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     }
205   }
206   // Create new fields
207   for (int aFieldIndex = 0; aFieldIndex < aXao.countFields(); ++aFieldIndex) {
208     XAO::Field* aXaoField = aXao.getField(aFieldIndex);
209
210     std::shared_ptr<ModelAPI_Feature> aFieldFeature = addFeature("Field");
211
212     // group name
213     if (!aXaoField->getName().empty())
214       aFieldFeature->data()->setName(aXaoField->getName());
215
216     // fill selection
217     AttributeSelectionListPtr aSelectionList = aFieldFeature->selectionList("selected");
218
219     // conversion of dimension
220     std::string aDimensionString = XAO::XaoUtils::dimensionToString(aXaoField->getDimension());
221     std::string aSelectionType =
222       ExchangePlugin_Tools::xaoDimension2selectionType(aDimensionString);
223     aSelectionList->setSelectionType(aSelectionType);
224     // limitation: now in XAO fields are related to everything, so, iterate all sub-shapes to fill
225     int aCountSelected = aXaoField->countElements();
226     std::list<ResultPtr>::const_iterator aResIter = results().begin();
227     for(; aResIter != results().end() && aCountSelected; aResIter++) {
228       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
229       if (!aBody.get())
230         continue;
231       // check that only results that were created before this field are used
232       FeaturePtr aResultFeature = document()->feature(aBody);
233       if (!aResultFeature.get())
234         continue;
235       GeomShapePtr aShape = aBody->shape();
236       if (!aShape.get() || aShape->isNull())
237         continue;
238       GeomAPI_ShapeExplorer anExp(aShape, GeomAPI_Shape::shapeTypeByStr(aSelectionType));
239       for(; anExp.more(); anExp.next()) {
240         aSelectionList->append(aBody, anExp.current());
241         aCountSelected--;
242         if (aCountSelected == 0)
243           break;
244       }
245     }
246
247     // conversion of type
248     XAO::Type aFieldType = aXaoField->getType();
249     std::string aTypeString = XAO::XaoUtils::fieldTypeToString(aFieldType);
250     ModelAPI_AttributeTables::ValueType aType =
251       ExchangePlugin_Tools::xaoType2valuesType(aTypeString);
252     // set components names
253     AttributeStringArrayPtr aComponents = aFieldFeature->stringArray("components_names");
254     aComponents->setSize(aXaoField->countComponents());
255     for(int aComp = 0; aComp < aXaoField->countComponents(); aComp++) {
256       aComponents->setValue(aComp, aXaoField->getComponentName(aComp));
257     }
258
259     AttributeIntArrayPtr aStamps = aFieldFeature->intArray("stamps");
260     aStamps->setSize(aXaoField->countSteps());
261     std::shared_ptr<ModelAPI_AttributeTables> aTables = aFieldFeature->tables("values");
262     aTables->setSize(
263       aXaoField->countElements() + 1, aXaoField->countComponents(), aXaoField->countSteps());
264     aTables->setType(aType);
265     // iterate steps
266     XAO::stepIterator aStepIter = aXaoField->begin();
267     for(int aStepIndex = 0; aStepIter != aXaoField->end(); aStepIter++, aStepIndex++) {
268       aStamps->setValue(aStepIndex, (*aStepIter)->getStamp());
269       for(int aRow = 1; aRow <= aXaoField->countElements(); aRow++) {
270         for(int aCol = 0; aCol < aXaoField->countComponents(); aCol++) {
271           ModelAPI_AttributeTables::Value aVal;
272           std::string aValStr = (*aStepIter)->getStringValue(aRow - 1, aCol);
273           switch(aType) {
274           case ModelAPI_AttributeTables::BOOLEAN:
275             aVal.myBool = aValStr == "true";
276             break;
277           case ModelAPI_AttributeTables::INTEGER:
278             aVal.myInt = atoi(aValStr.c_str());
279             break;
280           case ModelAPI_AttributeTables::DOUBLE:
281             aVal.myDouble = atof(aValStr.c_str());
282             break;
283           case ModelAPI_AttributeTables::STRING:
284             aVal.myStr = aValStr;
285             break;
286           }
287           aTables->setValue(aVal, aRow, aCol, aStepIndex);
288         }
289       }
290     }
291     // remove everything with zero-values: zeroes are treated as defaults
292     std::set<int> aRowsToRemove;
293     for(int aRow = 1; aRow < aTables->rows(); aRow++) {
294       bool isZero = true;
295       for(int aCol = 0; aCol < aTables->columns() && isZero; aCol++) {
296         for(int aStepIndex = 0; aStepIndex != aTables->tables() && isZero; aStepIndex++) {
297           if (aTables->valueStr(aRow, aCol, aStepIndex) != aTables->valueStr(0, aCol, aStepIndex))
298             isZero = false;
299         }
300       }
301       if (isZero)
302         aRowsToRemove.insert(aRow - 1); // -1 to make prepared for remove from SelectionList
303     }
304     if (!aRowsToRemove.empty()) { // move usefull rows on bottom to the up of the tables
305       // number of rows passed during going through: the current rows will
306       // be moved up for this value
307       int aRemovedPassed = 0;
308       for(int aRow = 1; aRow < aTables->rows(); aRow++) {
309         if (aRowsToRemove.find(aRow - 1) != aRowsToRemove.end()) {
310           aRemovedPassed++;
311         } else if (aRemovedPassed != 0) { // copy the line up
312           for(int aCol = 0; aCol < aTables->columns(); aCol++) {
313             for(int aTable = 0; aTable != aTables->tables(); aTable++) {
314               aTables->setValue(
315                 aTables->value(aRow, aCol, aTable), aRow - aRemovedPassed, aCol, aTable);
316             }
317           }
318         }
319       }
320       aTables->setSize(aTables->rows() - aRemovedPassed, aTables->columns(), aTables->tables());
321       aSelectionList->remove(aRowsToRemove); // remove also selected elements
322     }
323   }
324   // Top avoid problems in Object Browser update: issue #1647.
325   ModelAPI_EventCreator::get()->sendReordered(
326     std::dynamic_pointer_cast<ModelAPI_Feature>(aRefListOfGroups->owner()));
327
328   } catch (XAO::XAO_Exception& e) {
329     std::string anError = e.what();
330     setError("An error occurred while importing " + theFileName + ": " + anError);
331     return;
332   }
333 }
334
335 //============================================================================
336 std::shared_ptr<ModelAPI_Feature> ExchangePlugin_ImportFeature::addFeature(
337     std::string theID)
338 {
339   std::shared_ptr<ModelAPI_Feature> aNew = document()->addFeature(theID, false);
340   if (aNew)
341     data()->reflist(FEATURES_ID())->append(aNew);
342   // set as current also after it becomes sub to set correctly enabled for other subs
343   //document()->setCurrentFeature(aNew, false);
344   return aNew;
345 }
346
347 void ExchangePlugin_ImportFeature::removeFeature(
348     std::shared_ptr<ModelAPI_Feature> theFeature)
349 {
350   if (!data()->isValid())
351     return;
352   AttributeRefListPtr aList = reflist(FEATURES_ID());
353   aList->remove(theFeature);
354 }
355
356 int ExchangePlugin_ImportFeature::numberOfSubs(bool forTree) const
357 {
358   return data()->reflist(FEATURES_ID())->size(true);
359 }
360
361 std::shared_ptr<ModelAPI_Feature> ExchangePlugin_ImportFeature::subFeature(
362     const int theIndex, bool forTree)
363 {
364   ObjectPtr anObj = data()->reflist(FEATURES_ID())->object(theIndex, false);
365   FeaturePtr aRes = std::dynamic_pointer_cast<ModelAPI_Feature>(anObj);
366   return aRes;
367 }
368
369 int ExchangePlugin_ImportFeature::subFeatureId(const int theIndex) const
370 {
371   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
372       ModelAPI_AttributeRefList>(data()->attribute(FEATURES_ID()));
373   std::list<ObjectPtr> aFeatures = aRefList->list();
374   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin();
375   int aResultIndex = 1; // number of the counted (created) features, started from 1
376   int aFeatureIndex = -1; // number of the not-empty features in the list
377   for (; anIt != aFeatures.end(); anIt++) {
378     if (anIt->get())
379       aFeatureIndex++;
380     if (aFeatureIndex == theIndex)
381       break;
382     aResultIndex++;
383   }
384   return aResultIndex;
385 }
386
387 bool ExchangePlugin_ImportFeature::isSub(ObjectPtr theObject) const
388 {
389   // check is this feature of result
390   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
391   if (aFeature)
392     return data()->reflist(FEATURES_ID())->isInList(aFeature);
393   return false;
394 }
395
396 //============================================================================
397 void ExchangePlugin_ImportFeature::loadNamingDS(
398     std::shared_ptr<GeomAPI_Shape> theGeomShape,
399     std::shared_ptr<ModelAPI_ResultBody> theResultBody)
400 {
401   //load result
402   theResultBody->store(theGeomShape);
403
404   int aTag(1);
405   std::string aNameMS = "Shape";
406   theResultBody->loadFirstLevel(theGeomShape, aNameMS);
407 }