Salome HOME
Issue #1489 Multi-rotation problem if there is a reference to copied objects
[modules/shaper.git] / src / ModelAPI / ModelAPI_Tools.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        ModelAPI_Tools.cpp
4 // Created:     06 Aug 2014
5 // Author:      Vitaly Smetannikov
6
7 #include "ModelAPI_Tools.h"
8 #include <ModelAPI_Session.h>
9 #include <ModelAPI_Document.h>
10 #include <ModelAPI_Object.h>
11 #include <ModelAPI_AttributeDouble.h>
12 #include <ModelAPI_ResultParameter.h>
13 #include <ModelAPI_ResultPart.h>
14 #include <ModelAPI_AttributeDocRef.h>
15 #include <list>
16 #include <map>
17 #include <iostream>
18
19 #include <Events_Loop.h>
20 #include <ModelAPI_Events.h>
21
22 //#define DEBUG_REMOVE_FEATURES
23
24 #ifdef DEBUG_REMOVE_FEATURES
25 void printMapInfo(const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
26                   const std::string& thePrefix)
27 {
28   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = theMainList.begin(),
29                                                               aMainLast = theMainList.end();
30   std::string anInfo;
31   for (; aMainIt != aMainLast; aMainIt++) {
32     FeaturePtr aMainListFeature = aMainIt->first;
33     std::set<FeaturePtr> aMainRefList = aMainIt->second;
34     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(), aLast = aMainRefList.end();
35     std::string aRefsInfo;
36     for (; anIt != aLast; anIt++) {
37       aRefsInfo += (*anIt)->name().c_str();
38       if (anIt != aLast)
39         aRefsInfo += ", ";
40     }
41     if (!aRefsInfo.empty()) {
42       anInfo = anInfo + aMainListFeature->name().c_str() + ": " + aRefsInfo + "\n";
43     }
44   }
45   std::cout << thePrefix.c_str() << ": " << anInfo.c_str() << std::endl;
46 }
47
48 void printListInfo(const std::set<FeaturePtr>& theMainList,
49                   const std::string& thePrefix)
50 {
51   std::set<FeaturePtr>::const_iterator aMainIt = theMainList.begin(),
52                                        aMainLast = theMainList.end();
53   std::string anInfo;
54   for (; aMainIt != aMainLast; aMainIt++) {
55     FeaturePtr aRefFeature = *aMainIt;
56     anInfo += aRefFeature->name().c_str();
57     if (aMainIt != aMainLast)
58       anInfo += ", ";
59   }
60   std::cout << thePrefix.c_str() << ": " << anInfo.c_str() << std::endl;
61 }
62 #endif
63
64 namespace ModelAPI_Tools {
65
66 std::shared_ptr<GeomAPI_Shape> shape(const ResultPtr& theResult)
67 {
68   return theResult->shape();
69 }
70
71 const char* toString(ModelAPI_ExecState theExecState) 
72 {
73 #define TO_STRING(__NAME__) case __NAME__: return #__NAME__;
74   switch (theExecState) {
75   TO_STRING(ModelAPI_StateDone)
76   TO_STRING(ModelAPI_StateMustBeUpdated)
77   TO_STRING(ModelAPI_StateExecFailed)
78   TO_STRING(ModelAPI_StateInvalidArgument)
79   TO_STRING(ModelAPI_StateNothing)
80   default: return "Unknown ExecState.";
81   }
82 #undef TO_STRING
83 }
84
85 std::string getFeatureError(const FeaturePtr& theFeature)
86 {
87   std::string anError;
88   if (!theFeature.get() || !theFeature->data()->isValid() || theFeature->isAction())
89     return anError;
90
91   // to be removed later, this error should be got from the feature
92   if (theFeature->data()->execState() == ModelAPI_StateDone ||
93       theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
94     return anError;
95
96   // set error indication
97   anError = theFeature->error();
98   if (anError.empty()) {
99     bool isDone = ( theFeature->data()->execState() == ModelAPI_StateDone
100                  || theFeature->data()->execState() == ModelAPI_StateMustBeUpdated );
101     if (!isDone) {
102       anError = toString(theFeature->data()->execState());
103       // If the feature is Composite and error is StateInvalidArgument,
104       // error text should include error of first invalid sub-feature. Otherwise
105       // it is not clear what is the reason of the invalid argument.
106       if (theFeature->data()->execState() == ModelAPI_StateInvalidArgument) {
107         CompositeFeaturePtr aComposite =
108                     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
109         if (aComposite) {
110           for (int i = 0, aSize = aComposite->numberOfSubs(); i < aSize; i++) {
111             FeaturePtr aSubFeature = aComposite->subFeature(i);
112             std::string aSubFeatureError = getFeatureError(aSubFeature);
113             if (!aSubFeatureError.empty()) {
114               anError = anError + " in " + aSubFeature->getKind() + ".\n" + aSubFeatureError;
115               break;
116             }
117           }
118         }
119       }
120     }
121   }
122
123   return anError;
124 }
125
126 ObjectPtr objectByName(const DocumentPtr& theDocument, const std::string& theGroup, const std::string& theName)
127 {
128   for (int anIndex = 0; anIndex < theDocument->size(theGroup); ++anIndex) {
129     ObjectPtr anObject = theDocument->object(theGroup, anIndex);
130     if (anObject->data()->name() == theName)
131       return anObject;
132   }
133   // not found
134   return ObjectPtr();
135 }
136
137 bool findVariable(const DocumentPtr& theDocument, FeaturePtr theSearcher,
138                   const std::string& theName, double& outValue, ResultParameterPtr& theParam)
139 {
140   ObjectPtr aParamObj = objectByName(theDocument, ModelAPI_ResultParameter::group(), theName);
141   theParam = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aParamObj);
142   if (!theParam.get())
143     return false;
144   // avoid usage of parameters created later than the initial parameter
145   if (theSearcher.get() && theDocument->isLater(theDocument->feature(theParam), theSearcher))
146     return false;
147   AttributeDoublePtr aValueAttribute = theParam->data()->real(ModelAPI_ResultParameter::VALUE());
148   outValue = aValueAttribute->value();
149   return true;
150 }
151
152 bool findVariable(FeaturePtr theSearcher, const std::string& theName, double& outValue, ResultParameterPtr& theParam,
153                   const DocumentPtr& theDocument)
154 {
155   SessionPtr aSession = ModelAPI_Session::get();
156   std::list<DocumentPtr> aDocList;
157   DocumentPtr aDocument = theDocument.get() ? theDocument : aSession->activeDocument();
158   if (findVariable(aDocument, theSearcher, theName, outValue, theParam))
159     return true;
160   DocumentPtr aRootDocument = aSession->moduleDocument();
161   if (aDocument != aRootDocument) {
162     ResultPtr aPartResult = findPartResult(aRootDocument, aDocument);
163     if (aPartResult.get()) {
164       FeaturePtr aPartFeature;
165       if (theSearcher.get()) // only if the relative search is needed
166         aPartFeature = aRootDocument->feature(aPartResult);
167       if (findVariable(aRootDocument, aPartFeature, theName, outValue, theParam))
168         return true;
169     }
170   }
171   return false;
172 }
173
174 static std::map<int, std::vector<int> > myColorMap;
175
176 void appendValues(std::vector<int>& theRGB, const int theRed, const int theGreen, const int theBlue)
177 {
178   theRGB.push_back(theRed);
179   theRGB.push_back(theGreen);
180   theRGB.push_back(theBlue);
181 }
182
183 bool containsValues(std::map<int, std::vector<int> >& theColorMap, std::vector<int>& theValues)
184 {
185   std::map<int, std::vector<int> >::const_iterator anIt = theColorMap.begin(), aLast = theColorMap.end();
186   bool isFound = false;
187   for (; anIt != aLast && !isFound; anIt++) {
188     std::vector<int> aValues = anIt->second;
189     isFound = aValues[0] == theValues[0] &&
190               aValues[1] == theValues[1] &&
191               aValues[2] == theValues[2];
192   }
193   return isFound;
194 }
195
196 std::vector<int> HSVtoRGB(int theH, int theS, int theV)
197 {
198   std::vector<int> aRGB;
199   if (theH < 0 || theH > 360 ||
200       theS < 0 || theS > 100 ||
201       theV < 0 || theV > 100)
202     return aRGB;
203
204   int aHi = (int)theH/60;
205
206   double aV = theV;
207   double aVmin = (100 - theS)*theV/100;
208
209   double anA = (theV - aVmin)* (theH % 60) / 60;
210
211   double aVinc = aVmin + anA;
212   double aVdec = theV - anA;
213
214   double aPercentToValue = 255./100;
215   int aV_int    = (int)(aV*aPercentToValue);
216   int aVinc_int = (int)(aVinc*aPercentToValue);
217   int aVmin_int = (int)(aVmin*aPercentToValue);
218   int aVdec_int = (int)(aVdec*aPercentToValue);
219
220   switch(aHi) {
221     case 0: appendValues(aRGB, aV_int,    aVinc_int, aVmin_int); break;
222     case 1: appendValues(aRGB, aVdec_int, aV_int,    aVmin_int); break;
223     case 2: appendValues(aRGB, aVmin_int, aV_int,    aVinc_int); break;
224     case 3: appendValues(aRGB, aVmin_int, aVdec_int, aV_int); break;
225     case 4: appendValues(aRGB, aVinc_int, aVmin_int, aV_int); break;
226     case 5: appendValues(aRGB, aV_int,    aVmin_int, aVdec_int); break;
227     default: break;
228   }
229   return aRGB;
230 }
231
232
233 void fillColorMap()
234 {
235   if (!myColorMap.empty())
236     return;
237
238   int i = 0;
239   for (int s = 100; s > 0; s = s - 50)
240   {
241     for (int v = 100; v >= 40; v = v - 20)
242     {
243       for (int h = 0; h < 359 ; h = h + 60)
244       {
245         std::vector<int> aColor = HSVtoRGB(h, s, v);
246         if (containsValues(myColorMap, aColor))
247           continue;
248         myColorMap[i] = aColor;
249         i++;
250       }
251     }
252   }
253 }
254
255 void findRandomColor(std::vector<int>& theValues)
256 {
257   theValues.clear();
258   if (myColorMap.empty()) {
259     fillColorMap();
260   }
261
262   size_t aSize = myColorMap.size();
263   int anIndex = rand() % aSize;
264   if (myColorMap.find(anIndex) != myColorMap.end()) {
265     theValues = myColorMap.at(anIndex);
266   }
267 }
268
269 ResultPtr findPartResult(const DocumentPtr& theMain, const DocumentPtr& theSub)
270 {
271   if (theMain != theSub) { // to optimize and avoid of crash on partset document close (don't touch the sub-document structure)
272     for (int a = theMain->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
273       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
274           theMain->object(ModelAPI_ResultPart::group(), a));
275       if (aPart && aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->value() == theSub) {
276         return aPart;
277       }
278     }
279   }
280   return ResultPtr();
281 }
282
283 FeaturePtr findPartFeature(const DocumentPtr& theMain, const DocumentPtr& theSub)
284 {
285   if (theMain != theSub) { // to optimize and avoid of crash on partset document close (don't touch the sub-document structure)
286     for (int a = theMain->size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
287       FeaturePtr aPartFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(
288           theMain->object(ModelAPI_Feature::group(), a));
289       if (aPartFeat.get()) {
290         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aPartFeat->results();
291         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
292         for(; aRes != aResList.end(); aRes++) {
293           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
294           if (aPart.get()) {
295             if (aPart->isActivated() && aPart->partDoc() == theSub)
296               return aPartFeat;
297           } else break; // if the first is not Part, others are also not
298         }
299       }
300     }
301   }
302   return FeaturePtr();
303 }
304
305 CompositeFeaturePtr compositeOwner(const FeaturePtr& theFeature)
306 {
307   if (theFeature.get() && theFeature->data()->isValid()) {
308     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
309     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.begin();
310     for(; aRefIter != aRefs.end(); aRefIter++) {
311       CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>
312         ((*aRefIter)->owner());
313       if (aComp.get() && aComp->data()->isValid() && aComp->isSub(theFeature))
314         return aComp;
315     }
316   }
317   return CompositeFeaturePtr(); // not found
318 }
319
320 ResultCompSolidPtr compSolidOwner(const ResultPtr& theSub)
321 {
322   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSub);
323   if (aBody.get()) {
324     FeaturePtr aFeatureOwner = aBody->document()->feature(aBody);
325     if (aFeatureOwner.get()) {
326       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter = 
327         aFeatureOwner->results().cbegin();
328       for(; aResIter != aFeatureOwner->results().cend(); aResIter++) {
329         ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aResIter);
330         if (aComp && aComp->isSub(aBody))
331           return aComp;
332       }
333     }
334   }
335   return ResultCompSolidPtr(); // not found
336 }
337
338 bool hasSubResults(const ResultPtr& theResult)
339 {
340   ResultCompSolidPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theResult);
341   return aCompSolid.get() && aCompSolid->numberOfSubs() > 0;
342 }
343
344 void allResults(const FeaturePtr& theFeature, std::list<ResultPtr>& theResults)
345 {
346   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
347   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
348   for (; aRIter != aResults.cend(); aRIter++) {
349     theResults.push_back(*aRIter);
350     // iterate sub-bodies of compsolid
351     ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
352     if (aComp.get()) {
353       int aNumSub = aComp->numberOfSubs();
354       for(int a = 0; a < aNumSub; a++) {
355         theResults.push_back(aComp->subResult(a));
356       }
357     }
358   }
359 }
360
361 bool removeFeaturesAndReferences(const std::set<FeaturePtr>& theFeatures,
362                                  const bool theFlushRedisplay,
363                                  const bool theUseComposite,
364                                  const bool theUseRecursion)
365 {
366 #ifdef DEBUG_REMOVE_FEATURES
367   printListInfo(theFeatures, "selection: ");
368 #endif
369
370   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
371   ModelAPI_Tools::findAllReferences(theFeatures, aReferences, theUseComposite, theUseRecursion);
372 #ifdef DEBUG_REMOVE_FEATURES
373   printMapInfo(aReferences, "allDependencies: ");
374 #endif
375
376   std::set<FeaturePtr> aFeaturesRefsTo;
377   ModelAPI_Tools::findRefsToFeatures(theFeatures, aReferences, aFeaturesRefsTo);
378 #ifdef DEBUG_REMOVE_FEATURES
379   printListInfo(aFeaturesRefsTo, "references: ");
380 #endif
381
382   std::set<FeaturePtr> aFeatures = theFeatures;
383   if (!aFeaturesRefsTo.empty())
384     aFeatures.insert(aFeaturesRefsTo.begin(), aFeaturesRefsTo.end());
385 #ifdef DEBUG_REMOVE_FEATURES
386   printListInfo(aFeatures, "removeFeatures: ");
387 #endif
388
389   return ModelAPI_Tools::removeFeatures(aFeatures, false);
390 }
391
392 bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
393                     const bool theFlushRedisplay)
394 {
395   bool isDone = false;
396   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
397                                        aLast = theFeatures.end();
398   for (; anIt != aLast; anIt++) {
399     FeaturePtr aFeature = *anIt;
400     if (aFeature.get()) {
401       DocumentPtr aDoc = aFeature->document();
402       // flush REDISPLAY signal after remove feature
403       aDoc->removeFeature(aFeature);
404       isDone = true;
405     }
406   }
407   if (isDone && theFlushRedisplay) {
408     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
409     // if should be done after removeFeature() of document
410     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
411   }
412   return true;
413 }
414
415 // Fills the references list by all references of the feature from the references map.
416 // This is a recusive method to find references by next found feature in the map of references.
417 // \param theFeature a feature to find references
418 // \param theReferencesMap a map of references
419 // \param theReferences an out container of references
420 void addRefsToFeature(const FeaturePtr& theFeature,
421                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferencesMap,
422                       std::set<FeaturePtr>& theReferences)
423 {
424   if (theReferencesMap.find(theFeature) == theReferencesMap.end())
425     return; // this feature is not in the selection list, so exists without references to it
426   std::set<FeaturePtr> aMainReferences = theReferencesMap.at(theFeature);
427
428   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
429                                        aLast = aMainReferences.end();
430   for (; anIt != aLast; anIt++) {
431     FeaturePtr aRefFeature = *anIt;
432     if (theReferences.find(aRefFeature) == theReferences.end())
433       theReferences.insert(aRefFeature);
434     addRefsToFeature(aRefFeature, theReferencesMap, theReferences);
435   }
436 }
437
438 // For each feature from the feature list it searches references to the feature and append them
439 // to the references map. This is a recusive method.
440 // \param theFeature a feature to find references
441 // \param theReferencesMap a map of references
442 // \param theReferences an out container of references
443 void findReferences(const std::set<FeaturePtr>& theFeatures,
444                     std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
445                     const bool theUseComposite, const bool theUseRecursion)
446 {
447   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
448                                         aLast = theFeatures.end();
449   for (; anIt != aLast; anIt++) {
450     FeaturePtr aFeature = *anIt;
451     if (aFeature.get() && theReferences.find(aFeature) == theReferences.end()) {
452       DocumentPtr aSelFeatureDoc = aFeature->document();
453       std::set<FeaturePtr> aSelRefFeatures;
454       aSelFeatureDoc->refsToFeature(aFeature, aSelRefFeatures, false/*do not emit signals*/);
455       if (theUseComposite) { // do not filter selection
456         theReferences[aFeature] = aSelRefFeatures;
457       }
458       else { // filter references to skip composition features of the current feature
459         std::set<FeaturePtr> aFilteredFeatures;
460         std::set<FeaturePtr>::const_iterator anIt = aSelRefFeatures.begin(),
461                                              aLast = aSelRefFeatures.end();
462         for (; anIt != aLast; anIt++) {
463           FeaturePtr aCFeature = *anIt;
464           CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCFeature);
465           if (aComposite.get() && aComposite->isSub(aFeature))
466             continue; /// composite of the current feature should be skipped
467           aFilteredFeatures.insert(aCFeature);
468         }
469         theReferences[aFeature] = aFilteredFeatures;
470       }
471       if (theUseRecursion)
472         findReferences(aSelRefFeatures, theReferences, theUseComposite, theUseRecursion);
473     }
474   }
475 }
476
477 void findAllReferences(const std::set<FeaturePtr>& theFeatures,
478                        std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
479                        const bool theUseComposite,
480                        const bool theUseRecursion)
481 {
482   // For dependencies, find main_list:
483   // sk_1(ext_1, vertex_1)
484   // ext_1(bool_1, sk_3)
485   // vertex_1()
486   // sk_2(ext_2)
487   // ext_2(bool_2)
488   // sk_3()
489   // Information: bool_1 is not selected, ext_2(bool_2) exists
490   // find all referenced features
491   std::map<FeaturePtr, std::set<FeaturePtr> > aMainList;
492   findReferences(theFeatures, aMainList, theUseComposite, theUseRecursion);
493
494 #ifdef DEBUG_REMOVE_FEATURES
495   printMapInfo(aMainList, "firstDependencies");
496 #endif
497   // find all dependencies for each object:
498   // sk_1(ext_1, vertex_1) + (sk_3, bool_1)
499   // ext_1(bool_1, sk_3)
500   // vertex_1()
501   // sk_2(ext_2) + (bool_1)
502   // ext_2(bool_1)
503   // sk_3()
504   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aMainList.begin(),
505                                                               aMainLast = aMainList.end();
506   for (; aMainIt != aMainLast; aMainIt++) {
507     FeaturePtr aMainListFeature = aMainIt->first;
508     //std::string aName = aMainListFeature->name();
509     std::set<FeaturePtr> aMainRefList = aMainIt->second;
510     std::set<FeaturePtr> anAddRefFeatures;
511
512     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(),
513                                          aLast = aMainRefList.end();
514     for (; anIt != aLast; anIt++) {
515       FeaturePtr aFeature = *anIt;
516       addRefsToFeature(aFeature, aMainList, aMainRefList);
517     }
518     theReferences[aMainListFeature] = aMainRefList;
519   }
520
521 #ifdef DEBUG_REMOVE_FEATURES
522   printMapInfo(theReferences, "allDependencies");
523 #endif
524 }
525
526 void findRefsToFeatures(const std::set<FeaturePtr>& theFeatures,
527                         const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
528                         std::set<FeaturePtr>& theFeaturesRefsTo)
529 {
530   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
531                                        aLast = theFeatures.end();
532   for (; anIt != aLast; anIt++) {
533     FeaturePtr aFeature = *anIt;
534     if (theReferences.find(aFeature) == theReferences.end())
535       continue;
536     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
537     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
538     for (; aRefIt != aRefLast; aRefIt++) {
539       FeaturePtr aRefFeature = *aRefIt;
540       CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeature);
541       if (aComposite.get() && aComposite->isSub(aFeature))
542         continue; /// composite of the current feature should not be removed
543
544       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
545           theFeaturesRefsTo.find(aRefFeature) == theFeaturesRefsTo.end()) // it is not added
546         theFeaturesRefsTo.insert(aRefFeature);
547     }
548   }
549 }
550
551 } // namespace ModelAPI_Tools
552
553