Salome HOME
d1f6c4f17bbe88a2619731e5bb59c8c854be1183
[modules/shaper.git] / src / SketchSolver / SketchSolver_Storage.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SketchSolver_Storage.cpp
4 // Created: 30 Nov 2015
5 // Author:  Artem ZHIDKOV
6
7 #include <SketchSolver_Storage.h>
8 #include <SketchSolver_Manager.h>
9
10 #include <GeomDataAPI_Point2D.h>
11 #include <ModelAPI_AttributeRefAttr.h>
12 #include <ModelAPI_AttributeRefList.h>
13 #include <SketchPlugin_Arc.h>
14 #include <SketchPlugin_Circle.h>
15 #include <SketchPlugin_Line.h>
16 #include <SketchPlugin_Point.h>
17 #include <SketchPlugin_IntersectionPoint.h>
18 #include <SketchPlugin_ConstraintCoincidence.h>
19 #include <SketchPlugin_ConstraintMirror.h>
20 #include <SketchPlugin_ConstraintRigid.h>
21 #include <SketchPlugin_Projection.h>
22
23
24 /// \brief Verify two vectors of constraints are equal.
25 ///        Vectors differ by the order of elements are equal.
26 static bool isEqual(const std::list<ConstraintWrapperPtr>& theCVec1,
27                     const std::list<ConstraintWrapperPtr>& theCVec2);
28
29 /// \brief Convert result to feature or attribute
30 static void resultToFeatureOrAttribute(const ObjectPtr& theResult,
31     FeaturePtr& theFeature, AttributePtr& theAttribute);
32
33
34 void SketchSolver_Storage::addConstraint(ConstraintPtr        theConstraint,
35                                          ConstraintWrapperPtr theSolverConstraint)
36 {
37   if (theSolverConstraint) {
38     std::list<ConstraintWrapperPtr> aConstrList(1, theSolverConstraint);
39     addConstraint(theConstraint, aConstrList);
40   } else
41     addConstraint(theConstraint, std::list<ConstraintWrapperPtr>());
42 }
43
44 void SketchSolver_Storage::addConstraint(
45     ConstraintPtr                   theConstraint,
46     std::list<ConstraintWrapperPtr> theSolverConstraints)
47 {
48   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
49       aFound = myConstraintMap.find(theConstraint);
50   if (aFound == myConstraintMap.end() || !isEqual(aFound->second, theSolverConstraints))
51     setNeedToResolve(true);
52
53   if (theSolverConstraints.empty()) {
54     // constraint links to the empty list, add its attributes linked to the empty entities
55     std::list<AttributePtr> aRefAttrs =
56         theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
57     std::list<AttributePtr>::const_iterator anAttrIt = aRefAttrs.begin();
58     for (; anAttrIt != aRefAttrs.end(); ++anAttrIt) {
59       AttributeRefAttrPtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIt);
60       if (aRef->isObject()) {
61         FeaturePtr aFeature = ModelAPI_Feature::feature(aRef->object());
62         if (aFeature) addEntity(aFeature, EntityWrapperPtr());
63       } else
64         addEntity(aRef->attr(), EntityWrapperPtr());
65     }
66     std::list<AttributePtr> aRefLists =
67         theConstraint->data()->attributes(ModelAPI_AttributeRefList::typeId());
68     for (anAttrIt = aRefLists.begin(); anAttrIt != aRefLists.end(); ++anAttrIt) {
69       AttributeRefListPtr aRef = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(*anAttrIt);
70       std::list<ObjectPtr> anObj = aRef->list();
71       std::list<ObjectPtr>::iterator anIt = anObj.begin();
72       for (; anIt != anObj.end(); ++anIt) {
73         FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
74         if (aFeature) addEntity(aFeature, EntityWrapperPtr());
75       }
76     }
77   }
78   else if (theSolverConstraints.front()->type() != CONSTRAINT_PT_PT_COINCIDENT) {
79     // Do not add point-point coincidence, because it is already made by setting
80     // the same parameters for both points
81     std::list<ConstraintWrapperPtr>::iterator aCIt = theSolverConstraints.begin();
82     for (; aCIt != theSolverConstraints.end(); ++aCIt)
83       update(*aCIt);
84   }
85
86   if (!theSolverConstraints.empty() || aFound == myConstraintMap.end())
87     myConstraintMap[theConstraint] = theSolverConstraints;
88   // block events if necessary
89   if (myEventsBlocked && theConstraint && theConstraint->data() && theConstraint->data()->isValid())
90     theConstraint->data()->blockSendAttributeUpdated(myEventsBlocked);
91 }
92
93 static std::list<AttributePtr> pointAttributes(FeaturePtr theFeature)
94 {
95   std::list<AttributePtr> aPoints;
96   if (!theFeature->data() || !theFeature->data()->isValid())
97     return aPoints;
98   if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
99     aPoints.push_back(theFeature->attribute(SketchPlugin_Arc::CENTER_ID()));
100     aPoints.push_back(theFeature->attribute(SketchPlugin_Arc::START_ID()));
101     aPoints.push_back(theFeature->attribute(SketchPlugin_Arc::END_ID()));
102   }
103   else if (theFeature->getKind() == SketchPlugin_Circle::ID())
104     aPoints.push_back(theFeature->attribute(SketchPlugin_Circle::CENTER_ID()));
105   else if (theFeature->getKind() == SketchPlugin_Line::ID()) {
106     aPoints.push_back(theFeature->attribute(SketchPlugin_Line::START_ID()));
107     aPoints.push_back(theFeature->attribute(SketchPlugin_Line::END_ID()));
108   }
109   else if (theFeature->getKind() == SketchPlugin_Point::ID() ||
110            theFeature->getKind() == SketchPlugin_IntersectionPoint::ID())
111     aPoints.push_back(theFeature->attribute(SketchPlugin_Point::COORD_ID()));
112   return aPoints;
113 }
114
115 void SketchSolver_Storage::addEntity(FeaturePtr       theFeature,
116                                      EntityWrapperPtr theSolverEntity)
117 {
118   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator aFound = myFeatureMap.find(theFeature);
119   if (aFound == myFeatureMap.end() || !aFound->second ||
120      (theSolverEntity && !aFound->second->isEqual(theSolverEntity)))
121     setNeedToResolve(true); // the entity is new or modified
122
123   if (!theSolverEntity) {
124     // feature links to the empty entity, add its attributes
125     std::list<AttributePtr> aPntAttrs = pointAttributes(theFeature);
126     std::list<AttributePtr>::const_iterator anAttrIt = aPntAttrs.begin();
127     for (; anAttrIt != aPntAttrs.end(); ++anAttrIt)
128       addEntity(*anAttrIt, EntityWrapperPtr());
129     if (aFound == myFeatureMap.end())
130       myFeatureMap[theFeature] = theSolverEntity;
131   } else
132     myFeatureMap[theFeature] = theSolverEntity;
133
134   // block events if necessary
135   if (myEventsBlocked && theFeature->data() && theFeature->data()->isValid())
136     theFeature->data()->blockSendAttributeUpdated(myEventsBlocked);
137 }
138
139 void SketchSolver_Storage::addEntity(AttributePtr     theAttribute,
140                                      EntityWrapperPtr theSolverEntity)
141 {
142   std::map<AttributePtr, EntityWrapperPtr>::const_iterator aFound =
143     myAttributeMap.find(theAttribute);
144   if (aFound == myAttributeMap.end() || !aFound->second ||
145      (theSolverEntity && !aFound->second->isEqual(theSolverEntity)))
146     setNeedToResolve(true); // the entity is new or modified
147
148   if (theSolverEntity || aFound == myAttributeMap.end())
149     myAttributeMap[theAttribute] = theSolverEntity;
150   // block events if necessary
151   if (myEventsBlocked && theAttribute->owner() &&
152       theAttribute->owner()->data() && theAttribute->owner()->data()->isValid())
153     theAttribute->owner()->data()->blockSendAttributeUpdated(myEventsBlocked);
154 }
155
156
157 static bool isCopyInMulti(std::shared_ptr<SketchPlugin_Feature> theFeature,
158     const std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >& theConstraints)
159 {
160   if (!theFeature)
161     return false;
162   bool aResult = theFeature->isCopy();
163   if (aResult) {
164     const std::set<AttributePtr>& aRefs = theFeature->data()->refsToMe();
165     for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
166          aRefIt != aRefs.end() && aResult; ++aRefIt) {
167       FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
168       if ((anOwner->getKind() == SketchPlugin_ConstraintMirror::ID() &&
169           (*aRefIt)->id() == SketchPlugin_Constraint::ENTITY_C()) ||
170          (anOwner->getKind() == SketchPlugin_Projection::ID()))
171         aResult = false;
172     }
173   }
174   return aResult;
175 }
176
177 bool SketchSolver_Storage::update(FeaturePtr theFeature, const GroupID& theGroup, bool theForce)
178 {
179   bool isUpdated = false;
180   EntityWrapperPtr aRelated = entity(theFeature);
181   if (!aRelated) { // Feature is not exist, create it
182     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
183         std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
184     bool isCopy = isCopyInMulti(aSketchFeature, myConstraintMap);
185     // the feature is a copy in "Multi" constraint and does not used in other constraints
186     if (!theForce && isCopy && myFeatureMap.find(theFeature) == myFeatureMap.end())
187       return false;
188
189     std::list<EntityWrapperPtr> aSubs;
190     // Reserve the feature in the map of features (do not want to add several copies of it)
191     myFeatureMap[theFeature] = aRelated;
192     // Firstly, create/update its attributes
193     std::list<AttributePtr> anAttrs = pointAttributes(theFeature);
194     std::list<AttributePtr>::const_iterator anIt = anAttrs.begin();
195     for (; anIt != anAttrs.end(); ++anIt) {
196       if (!(*anIt)->isInitialized())
197         return false;
198       isUpdated = update(*anIt, theGroup, theForce) || isUpdated;
199       aSubs.push_back(entity(*anIt));
200     }
201     // If the feature is a circle, add its radius as a sub
202     if (theFeature->getKind() == SketchPlugin_Circle::ID()) {
203       AttributePtr aRadius = theFeature->attribute(SketchPlugin_Circle::RADIUS_ID());
204       isUpdated = update(aRadius, theGroup, theForce) || isUpdated;
205       aSubs.push_back(entity(aRadius));
206     }
207     // If the feature if circle or arc, we need to add normal of the sketch to the list of subs
208     if (theFeature->getKind() == SketchPlugin_Arc::ID() ||
209         theFeature->getKind() == SketchPlugin_Circle::ID()) {
210       EntityWrapperPtr aNormal = getNormal();
211       if (aNormal) aSubs.push_back(aNormal);
212     }
213     // Secondly, convert feature
214     BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
215     GroupID aGroup = theGroup != GID_UNKNOWN ? theGroup : myGroupID;
216     // Check external feature
217     if (aSketchFeature && (aSketchFeature->isExternal() || isCopy))
218       aGroup = GID_OUTOFGROUP;
219     aRelated = aBuilder->createFeature(theFeature, aSubs, aGroup);
220     if (!aRelated)
221       return false;
222     addEntity(theFeature, aRelated);
223   } else if (theGroup != GID_UNKNOWN)
224     changeGroup(aRelated, theGroup);
225   return update(aRelated) || isUpdated;
226 }
227
228 bool SketchSolver_Storage::update(AttributePtr theAttribute, const GroupID& theGroup, bool theForce)
229 {
230   if (!theAttribute->isInitialized())
231     return false;
232
233   AttributePtr anAttribute = theAttribute;
234   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(anAttribute);
235   if (aRefAttr) {
236     if (aRefAttr->isObject()) {
237       FeaturePtr aFeature;
238       resultToFeatureOrAttribute(aRefAttr->object(), aFeature, anAttribute);
239       if (aFeature)
240         return update(aFeature, theGroup, theForce);
241     } else {
242       anAttribute = aRefAttr->attr();
243       if (!anAttribute->isInitialized())
244         return false;
245     }
246   }
247
248   EntityWrapperPtr aRelated = entity(anAttribute);
249   if (!aRelated) { // Attribute is not exist, create it
250     // verify the attribute is a point of arc and add whole arc
251     if (anAttribute->owner()) {
252       FeaturePtr aFeature = ModelAPI_Feature::feature(anAttribute->owner());
253       if (aFeature->getKind() == SketchPlugin_Arc::ID() &&
254           myFeatureMap.find(aFeature) == myFeatureMap.end()) {
255         // Additional checking that all attributes are initialized
256         if (aFeature->attribute(SketchPlugin_Arc::CENTER_ID())->isInitialized() &&
257             aFeature->attribute(SketchPlugin_Arc::START_ID())->isInitialized() &&
258             aFeature->attribute(SketchPlugin_Arc::END_ID())->isInitialized()) {
259           return SketchSolver_Storage::update(aFeature, theGroup, theForce);
260         } else {
261           myFeatureMap[aFeature] = EntityWrapperPtr();
262           myExistArc = true;
263         }
264       }
265     }
266     BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
267     GroupID aGroup = theGroup != GID_UNKNOWN ? theGroup : myGroupID;
268     // Check attribute of external features
269     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
270         std::dynamic_pointer_cast<SketchPlugin_Feature>(anAttribute->owner());
271     if (aSketchFeature && (aSketchFeature->isExternal() ||
272         isCopyInMulti(aSketchFeature, myConstraintMap)))
273       aGroup = GID_OUTOFGROUP;
274     aRelated = aBuilder->createAttribute(anAttribute, aGroup);
275     if (!aRelated)
276       return false;
277     addEntity(anAttribute, aRelated);
278   } else if (theGroup != GID_UNKNOWN)
279     changeGroup(aRelated, theGroup);
280   return update(aRelated);
281 }
282
283
284
285 const std::list<ConstraintWrapperPtr>& SketchSolver_Storage::constraint(
286     const ConstraintPtr& theConstraint) const
287 {
288   static std::list<ConstraintWrapperPtr> aDummy;
289
290   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr>>::const_iterator
291       aFound = myConstraintMap.find(theConstraint);
292   if (aFound != myConstraintMap.end())
293     return aFound->second;
294   return aDummy;
295 }
296
297 const EntityWrapperPtr& SketchSolver_Storage::entity(const FeaturePtr& theFeature) const
298 {
299   static EntityWrapperPtr aDummy;
300
301   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator aFound = myFeatureMap.find(theFeature);
302   if (aFound != myFeatureMap.end())
303     return aFound->second;
304   return aDummy;
305 }
306
307 const EntityWrapperPtr& SketchSolver_Storage::entity(const AttributePtr& theAttribute) const
308 {
309   static EntityWrapperPtr aDummy;
310
311   std::map<AttributePtr, EntityWrapperPtr>::const_iterator
312       aFound = myAttributeMap.find(theAttribute);
313   if (aFound != myAttributeMap.end())
314     return aFound->second;
315
316   AttributeRefAttrPtr aRefAttr =
317       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
318   if (aRefAttr) {
319     if (aRefAttr->isObject()) {
320       FeaturePtr aFeature;
321       AttributePtr anAttribute;
322       resultToFeatureOrAttribute(aRefAttr->object(), aFeature, anAttribute);
323       if (aFeature)
324         return entity(aFeature);
325       else
326         return entity(anAttribute);
327     } else
328       return entity(aRefAttr->attr());
329   }
330   return aDummy;
331 }
332
333 bool SketchSolver_Storage::removeConstraint(ConstraintPtr theConstraint)
334 {
335   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::iterator
336       aFound = myConstraintMap.find(theConstraint);
337   if (aFound == myConstraintMap.end())
338     return true; // no constraint, already deleted
339
340   // Remove constraint
341   std::list<ConstraintWrapperPtr> aConstrList = aFound->second;
342   myConstraintMap.erase(aFound);
343   // Remove SolveSpace constraints
344   bool isFullyRemoved = true;
345   std::list<ConstraintWrapperPtr>::iterator anIt = aConstrList.begin();
346   while (anIt != aConstrList.end()) {
347     if (remove(*anIt)) {
348       std::list<ConstraintWrapperPtr>::iterator aRemoveIt = anIt++;
349       aConstrList.erase(aRemoveIt);
350     } else {
351       isFullyRemoved = false;
352       ++anIt;
353     }
354   }
355   return isFullyRemoved;
356 }
357
358 template <class ENT_TYPE>
359 static bool isUsed(ConstraintWrapperPtr theConstraint, ENT_TYPE theEntity)
360 {
361   if (!theConstraint || !theEntity)
362     return false;
363   std::list<EntityWrapperPtr>::const_iterator anEntIt = theConstraint->entities().begin();
364   for (; anEntIt != theConstraint->entities().end(); ++anEntIt)
365     if ((*anEntIt)->isBase(theEntity))
366       return true;
367   return false;
368 }
369
370 static bool isUsed(EntityWrapperPtr theFeature, AttributePtr theSubEntity)
371 {
372   if (!theFeature || !theSubEntity)
373     return false;
374   std::list<EntityWrapperPtr>::const_iterator aSubIt = theFeature->subEntities().begin();
375   for (; aSubIt != theFeature->subEntities().end(); ++aSubIt)
376     if ((*aSubIt)->isBase(theSubEntity))
377       return true;
378   return false;
379 }
380
381 static bool isUsed(FeaturePtr theFeature, AttributePtr theAttribute)
382 {
383   if (!theFeature || !theAttribute)
384     return false;
385   std::list<AttributePtr> anAttrList = theFeature->data()->attributes(std::string());
386   std::list<AttributePtr>::const_iterator anIt = anAttrList.begin();
387   for (; anIt != anAttrList.end(); ++anIt) {
388     if (*anIt == theAttribute)
389       return true;
390     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anIt);
391     if (aRefAttr && !aRefAttr->isObject() && aRefAttr->attr() == theAttribute)
392       return true;
393   }
394   return false;
395 }
396
397 bool SketchSolver_Storage::isUsed(FeaturePtr theFeature) const
398 {
399   if (myFeatureMap.find(theFeature) != myFeatureMap.end())
400     return true;
401   // check constraints
402   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
403       aCIt = myConstraintMap.begin();
404   std::list<ConstraintWrapperPtr>::const_iterator aCWIt;
405   for (; aCIt != myConstraintMap.end(); ++aCIt)
406     for (aCWIt = aCIt->second.begin(); aCWIt != aCIt->second.end(); ++aCWIt)
407       if (::isUsed(*aCWIt, theFeature))
408         return true;
409   // check attributes
410   std::list<AttributePtr> anAttrList = pointAttributes(theFeature);
411   std::list<AttributePtr>::const_iterator anIt = anAttrList.begin();
412   for (; anIt != anAttrList.end(); ++anIt)
413     if (isUsed(*anIt))
414       return true;
415   return false;
416 }
417
418 bool SketchSolver_Storage::isUsed(AttributePtr theAttribute) const
419 {
420   AttributePtr anAttribute = theAttribute;
421   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(anAttribute);
422   if (aRefAttr) {
423     if (aRefAttr->isObject())
424       return isUsed(ModelAPI_Feature::feature(aRefAttr->object()));
425     else
426       anAttribute = aRefAttr->attr();
427   }
428
429   if (myAttributeMap.find(theAttribute) != myAttributeMap.end())
430     return true;
431   // check in constraints
432   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
433       aCIt = myConstraintMap.begin();
434   std::list<ConstraintWrapperPtr>::const_iterator aCWIt;
435   for (; aCIt != myConstraintMap.end(); ++aCIt) {
436     for (aCWIt = aCIt->second.begin(); aCWIt != aCIt->second.end(); ++aCWIt)
437       if (::isUsed(*aCWIt, anAttribute))
438         return true;
439     // Additional check for the Fixed constraints, which have no wrapper associated.
440     if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
441         ::isUsed(FeaturePtr(aCIt->first), anAttribute))
442       return true;
443   }
444   // check in features
445   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator aFIt = myFeatureMap.begin();
446   for (; aFIt != myFeatureMap.end(); ++aFIt)
447     if (::isUsed(aFIt->second, anAttribute))
448       return true;
449   return false;
450 }
451
452
453 bool SketchSolver_Storage::removeEntity(FeaturePtr theFeature)
454 {
455   std::map<FeaturePtr, EntityWrapperPtr>::iterator aFound = myFeatureMap.find(theFeature);
456   if (aFound == myFeatureMap.end())
457     return true; // feature not found, nothing to delete
458
459   EntityWrapperPtr anEntity = aFound->second;
460   myFeatureMap.erase(aFound);
461
462   // Check if the feature is not used by constraints, remove it
463   if (!anEntity || (!isUsed(theFeature) && remove(anEntity)))
464     return true;
465
466   // feature is not removed, revert operation
467   myFeatureMap[theFeature] = anEntity;
468   update(anEntity);
469   return false;
470 }
471
472 bool SketchSolver_Storage::removeEntity(AttributePtr theAttribute)
473 {
474   std::map<AttributePtr, EntityWrapperPtr>::iterator aFound = myAttributeMap.find(theAttribute);
475   if (aFound == myAttributeMap.end())
476     return true; // attribute not found, nothing to delete
477
478   EntityWrapperPtr anEntity = aFound->second;
479   myAttributeMap.erase(aFound);
480
481   // Check if the attribute is not used by constraints and features, remove it
482   if (!anEntity || (!isUsed(theAttribute) && remove(anEntity)))
483     return true;
484
485   // attribute is not removed, revert operation
486   myAttributeMap[theAttribute] = anEntity;
487   update(anEntity);
488   return false;
489 }
490
491 // Merge groups containing given entities
492 static void mergeGroups(std::list<std::set<EntityWrapperPtr> >& theGroups,
493     const EntityWrapperPtr& theEntity1, const EntityWrapperPtr& theEntity2)
494 {
495   std::list<std::set<EntityWrapperPtr> >::iterator aFound1 = theGroups.end();
496   std::list<std::set<EntityWrapperPtr> >::iterator aFound2 = theGroups.end();
497   std::list<std::set<EntityWrapperPtr> >::iterator anIt = theGroups.begin();
498   for (; anIt != theGroups.end() && (aFound1 == theGroups.end() || aFound2 == theGroups.end());
499        ++anIt) {
500     if (anIt->find(theEntity1) != anIt->end())
501       aFound1 = anIt;
502     if (anIt->find(theEntity2) != anIt->end())
503       aFound2 = anIt;
504   }
505
506   if (aFound1 == aFound2 || aFound1 == theGroups.end() || aFound2 == theGroups.end())
507     return; // nothing to merge
508
509   aFound1->insert(aFound2->begin(), aFound2->end());
510   theGroups.erase(aFound2);
511 }
512
513 bool SketchSolver_Storage::removeCoincidence(ConstraintWrapperPtr theConstraint)
514 {
515   std::list<EntityWrapperPtr> aPoints = theConstraint->entities();
516   std::list<EntityWrapperPtr>::const_iterator aPIt;
517
518   CoincidentPointsMap::iterator aPtPtIt = myCoincidentPoints.begin();
519   for (; aPtPtIt != myCoincidentPoints.end(); ++aPtPtIt) {
520     for (aPIt = aPoints.begin(); aPIt != aPoints.end(); ++aPIt)
521       if (aPtPtIt->first == *aPIt ||
522           aPtPtIt->second.find(*aPIt) != aPtPtIt->second.end())
523         break;
524     if (aPIt != aPoints.end())
525       break;
526   }
527
528   if (aPtPtIt == myCoincidentPoints.end())
529     return true; // already removed
530
531   // Removing of coincidence may split this group of coincident point to several groups.
532   // Find all of them and also the points which become alone.
533   std::list< std::set<EntityWrapperPtr> > aCoincGroups;
534   std::set<EntityWrapperPtr> aGroup;
535   aGroup.insert(aPtPtIt->first);
536   aCoincGroups.push_back(aGroup);
537   std::set<EntityWrapperPtr>::const_iterator aTempIt = aPtPtIt->second.begin();
538   for (; aTempIt != aPtPtIt->second.end(); ++aTempIt) {
539     aGroup.clear();
540     aGroup.insert(*aTempIt);
541     aCoincGroups.push_back(aGroup);
542   }
543
544   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::iterator
545       aConstrIt = myConstraintMap.begin();
546   for (; aConstrIt != myConstraintMap.end(); ++aConstrIt) {
547     if (aConstrIt->first->getKind() != SketchPlugin_ConstraintCoincidence::ID())
548       continue;
549
550     AttributeRefAttrPtr aRefAttr[2] = {
551         aConstrIt->first->refattr(SketchPlugin_Constraint::ENTITY_A()),
552         aConstrIt->first->refattr(SketchPlugin_Constraint::ENTITY_B())
553     };
554     AttributePtr anAttr[2];
555     if (aConstrIt->first->data()->isValid()) {
556       if (!aRefAttr[0] || !aRefAttr[1])
557         continue;
558
559       for (int i = 0; i < 2; ++i) {
560         if (aRefAttr[i]->isObject()) {
561           FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr[i]->object());
562           if (!aFeature || (aFeature->getKind() != SketchPlugin_Point::ID() &&
563               aFeature->getKind() != SketchPlugin_IntersectionPoint::ID()))
564             continue;
565           anAttr[i] = aFeature->attribute(SketchPlugin_Point::COORD_ID());
566         } else
567           anAttr[i] = aRefAttr[i]->attr();
568       }
569     } else {
570       // obtain attributes from the constraint wrapper
571       // if SketchPlugin_Constraint has invalid data (already removed)
572       ConstraintWrapperPtr aWrapper = aConstrIt->second.front();
573       anAttr[0] = aWrapper->entities().front()->baseAttribute();
574       anAttr[1] = aWrapper->entities().back()->baseAttribute();
575     }
576
577     EntityWrapperPtr anEntities[2];
578     for (int i = 0; i < 2; ++i) {
579       std::map<AttributePtr, EntityWrapperPtr>::iterator
580           aFound = myAttributeMap.find(anAttr[i]);
581       if (aFound != myAttributeMap.end())
582         anEntities[i] = aFound->second;
583     }
584     mergeGroups(aCoincGroups, anEntities[0], anEntities[1]);
585   }
586
587   // Collect alone points and build them new instances
588   std::list<EntityWrapperPtr> aShutOffList;
589   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
590   std::map<EntityWrapperPtr, EntityWrapperPtr> aNotCoinc;
591   std::list<std::set<EntityWrapperPtr> >::iterator aGroupIt = aCoincGroups.begin();
592   while (aGroupIt != aCoincGroups.end()) {
593     if (aGroupIt->size() == 1) {
594       EntityWrapperPtr aPoint = *aGroupIt->begin();
595       aShutOffList.push_back(aPoint);
596       aNotCoinc[aPoint] =
597           aBuilder->createAttribute(aPoint->baseAttribute(), myGroupID, mySketchID);
598       std::list<std::set<EntityWrapperPtr> >::iterator aRemoveIt = aGroupIt++;
599       aCoincGroups.erase(aRemoveIt);
600     } else // point is not alone
601       ++aGroupIt;
602   }
603
604   if (aNotCoinc.empty() && aCoincGroups.size() == 1)
605     return false;
606
607   // Find all features and constraints uses non-coincident points
608   replaceEntities(aNotCoinc);
609
610   // Remove not coincident points and points in separated groups
611   if (!aCoincGroups.empty()) {
612     aGroupIt = aCoincGroups.begin();
613     for (++aGroupIt; aGroupIt != aCoincGroups.end(); ++aGroupIt)
614       aShutOffList.insert(aShutOffList.end(), aGroupIt->begin(), aGroupIt->end());
615   }
616   std::list<EntityWrapperPtr>::iterator aNotCIt = aShutOffList.begin();
617   for (; aNotCIt != aShutOffList.end(); ++aNotCIt) {
618     if (aPtPtIt->second.size() <= 1) {
619       myCoincidentPoints.erase(aPtPtIt);
620       break;
621     }
622     if (aPtPtIt->first == *aNotCIt) {
623       std::set<EntityWrapperPtr> aSlaves = aPtPtIt->second;
624       EntityWrapperPtr aNewMaster = *aSlaves.begin();
625       aSlaves.erase(aSlaves.begin());
626       myCoincidentPoints.erase(aPtPtIt);
627       myCoincidentPoints[aNewMaster] = aSlaves;
628       aPtPtIt = myCoincidentPoints.find(aNewMaster);
629     } else
630       aPtPtIt->second.erase(*aNotCIt);
631   }
632
633   // Create additional groups of coincident points
634   aGroupIt = aCoincGroups.begin();
635   if (!aCoincGroups.empty())
636     ++aGroupIt;
637   for (; aGroupIt != aCoincGroups.end(); ++aGroupIt) {
638     aNotCoinc.clear();
639     std::set<EntityWrapperPtr>::iterator anEntIt = aGroupIt->begin();
640     for (; anEntIt != aGroupIt->end(); ++anEntIt) {
641       aNotCoinc[*anEntIt] =
642           aBuilder->createAttribute((*anEntIt)->baseAttribute(), myGroupID, mySketchID);
643     }
644     // replace points by newly created
645     replaceEntities(aNotCoinc);
646     // set new group of coincident points
647     EntityWrapperPtr aMasterEnt = aNotCoinc.begin()->second;
648     std::map<EntityWrapperPtr, EntityWrapperPtr>::iterator aNCIt = aNotCoinc.begin();
649     for (++aNCIt; aNCIt != aNotCoinc.end(); ++aNCIt)
650       addCoincidentPoints(aMasterEnt, aNCIt->second);
651   }
652
653   return true;
654 }
655
656 void SketchSolver_Storage::replaceEntities(const std::map<EntityWrapperPtr,
657                                            EntityWrapperPtr>& theChange)
658 {
659   std::set<EntityWrapperPtr> anUpdFeatures;
660   std::map<EntityWrapperPtr, EntityWrapperPtr>::const_iterator aSubIt;
661   std::map<FeaturePtr, EntityWrapperPtr>::iterator aFIt = myFeatureMap.begin();
662   for (; aFIt != myFeatureMap.end(); ++aFIt) {
663     if (!aFIt->second)
664       continue; // avoid not completed arcs
665     for (aSubIt = theChange.begin(); aSubIt != theChange.end(); ++aSubIt) {
666       if (!aSubIt->second || !::isUsed(aFIt->first, aSubIt->first->baseAttribute()))
667         continue;
668       std::list<EntityWrapperPtr> aSubs = aFIt->second->subEntities();
669       std::list<EntityWrapperPtr>::iterator aSIt = aSubs.begin();
670       bool isUpd = false;
671       for (; aSIt != aSubs.end(); ++aSIt)
672         if (*aSIt == aSubIt->first) {
673           (*aSIt)->update(aSubIt->second);
674           (*aSIt)->setGroup(aFIt->second->group());
675           isUpd = true;
676         }
677       if (isUpd) {
678         aFIt->second->setSubEntities(aSubs);
679         anUpdFeatures.insert(aFIt->second);
680       }
681     }
682   }
683   // update features
684   std::set<EntityWrapperPtr>::iterator anUpdIt = anUpdFeatures.begin();
685   for (; anUpdIt != anUpdFeatures.end(); ++anUpdIt)
686     update(EntityWrapperPtr(*anUpdIt));
687 }
688
689 bool SketchSolver_Storage::remove(ConstraintWrapperPtr theConstraint)
690 {
691   bool isFullyRemoved = true;
692   std::list<EntityWrapperPtr>::const_iterator anIt = theConstraint->entities().begin();
693   for (; anIt != theConstraint->entities().end(); ++anIt) {
694     FeaturePtr aBaseFeature = (*anIt)->baseFeature();
695     if (aBaseFeature)
696       isFullyRemoved = SketchSolver_Storage::removeEntity(aBaseFeature) && isFullyRemoved;
697     else
698       isFullyRemoved =
699         SketchSolver_Storage::removeEntity((*anIt)->baseAttribute()) && isFullyRemoved;
700   }
701   return isFullyRemoved;
702 }
703
704 bool SketchSolver_Storage::remove(EntityWrapperPtr theEntity)
705 {
706   bool isFullyRemoved = true;
707   std::list<EntityWrapperPtr>::const_iterator anEntIt = theEntity->subEntities().begin();
708   for (; anEntIt != theEntity->subEntities().end(); ++anEntIt) {
709     FeaturePtr aBaseFeature = (*anEntIt)->baseFeature();
710     if (aBaseFeature)
711       isFullyRemoved = SketchSolver_Storage::removeEntity(aBaseFeature) && isFullyRemoved;
712     else {
713       AttributePtr aBaseAttr = (*anEntIt)->baseAttribute();
714       if (aBaseAttr)
715         isFullyRemoved = SketchSolver_Storage::removeEntity(aBaseAttr) && isFullyRemoved;
716       else
717         remove(*anEntIt);
718     }
719   }
720
721   std::list<ParameterWrapperPtr>::const_iterator aParIt = theEntity->parameters().begin();
722   for (; aParIt != theEntity->parameters().end(); ++aParIt)
723     isFullyRemoved = remove(*aParIt) && isFullyRemoved;
724   return isFullyRemoved;
725 }
726
727
728 bool SketchSolver_Storage::isInteract(const FeaturePtr& theFeature) const
729 {
730   if (!theFeature)
731     return false;
732   if (myConstraintMap.empty())
733     return true; // empty storage interacts with each feature
734
735   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
736   if (aConstraint) {
737     if (myConstraintMap.find(aConstraint) != myConstraintMap.end())
738       return true;
739   } else if (myFeatureMap.find(theFeature) != myFeatureMap.end())
740     return true;
741
742   std::list<AttributePtr> anAttrList = theFeature->data()->attributes(std::string());
743   std::list<AttributePtr>::const_iterator anIt = anAttrList.begin();
744   for (; anIt != anAttrList.end(); ++anIt)
745     if (isInteract(*anIt))
746       return true;
747
748   return false;
749 }
750
751 bool SketchSolver_Storage::isInteract(const AttributePtr& theAttribute) const
752 {
753   if (!theAttribute)
754     return false;
755
756   AttributeRefListPtr aRefList =
757       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(theAttribute);
758   if (aRefList) {
759     std::list<ObjectPtr> anObjects = aRefList->list();
760     std::list<ObjectPtr>::iterator anObjIt = anObjects.begin();
761     for (; anObjIt != anObjects.end(); ++anObjIt) {
762       FeaturePtr aFeature = ModelAPI_Feature::feature(*anObjIt);
763       if (isInteract(aFeature))
764         return true;
765     }
766     return false;
767   }
768
769   AttributeRefAttrPtr aRefAttr =
770       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
771   if (!aRefAttr)
772     return myAttributeMap.find(theAttribute) != myAttributeMap.end();
773   if (!aRefAttr->isObject())
774     return myAttributeMap.find(aRefAttr->attr()) != myAttributeMap.end();
775
776   FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
777   return isInteract(aFeature);
778 }
779
780 bool SketchSolver_Storage::isConsistent() const
781 {
782   // Check the constraints are valid
783   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
784       aCIter = myConstraintMap.begin();
785   for (; aCIter != myConstraintMap.end(); ++aCIter)
786     if (!aCIter->first->data() || !aCIter->first->data()->isValid())
787       return false;
788   // Check the features are valid
789   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator aFIter = myFeatureMap.begin();
790   for (; aFIter != myFeatureMap.end(); aFIter++)
791     if (!aFIter->first->data() || !aFIter->first->data()->isValid())
792       return false;
793   return true;
794 }
795
796 bool SketchSolver_Storage::isFixed(EntityWrapperPtr theEntity) const
797 {
798   if (theEntity->group() != myGroupID)
799     return true;
800   // no need additional checking for entities differ than point
801   if (theEntity->type() != ENTITY_POINT)
802     return false;
803
804   CoincidentPointsMap::const_iterator anIt = myCoincidentPoints.begin();
805   for (; anIt != myCoincidentPoints.end(); ++anIt)
806     if (anIt->first == theEntity || anIt->second.find(theEntity) != anIt->second.end()) {
807       if (anIt->first->group() != myGroupID)
808         return true;
809       std::set<EntityWrapperPtr>::const_iterator anEntIt = anIt->second.begin();
810       for (; anEntIt != anIt->second.end(); ++anEntIt)
811         if ((*anEntIt)->group() != myGroupID)
812           return true;
813     }
814
815   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator aCIt =
816     myConstraintMap.begin();
817   std::list<ConstraintWrapperPtr>::const_iterator aCWIt;
818   for (; aCIt != myConstraintMap.end(); ++aCIt) {
819     if (aCIt->second.empty())
820       continue;
821     aCWIt = aCIt->second.begin();
822     if ((*aCWIt)->type() != CONSTRAINT_FIXED)
823       continue;
824     for (; aCWIt != aCIt->second.end(); ++aCIt)
825       if ((theEntity->baseAttribute() && (*aCWIt)->isUsed(theEntity->baseAttribute())) ||
826           (theEntity->baseFeature() && (*aCWIt)->isUsed(theEntity->baseFeature())))
827         return true;
828   }
829
830   return false;
831 }
832
833 void SketchSolver_Storage::removeInvalidEntities()
834 {
835   // Remove invalid constraints
836   std::list<ConstraintPtr> anInvalidConstraints;
837   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
838       aCIter = myConstraintMap.begin();
839   for (; aCIter != myConstraintMap.end(); ++aCIter)
840     if (!aCIter->first->data() || !aCIter->first->data()->isValid())
841       anInvalidConstraints.push_back(aCIter->first);
842   std::list<ConstraintPtr>::const_iterator anInvCIt = anInvalidConstraints.begin();
843   for (; anInvCIt != anInvalidConstraints.end(); ++anInvCIt)
844     removeConstraint(*anInvCIt);
845   // Remove invalid features
846   std::list<FeaturePtr> anInvalidFeatures;
847   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator aFIter = myFeatureMap.begin();
848   for (; aFIter != myFeatureMap.end(); aFIter++)
849     if (!aFIter->first->data() || !aFIter->first->data()->isValid())
850       anInvalidFeatures.push_back(aFIter->first);
851   std::list<FeaturePtr>::const_iterator anInvFIt = anInvalidFeatures.begin();
852   for (; anInvFIt != anInvalidFeatures.end(); ++anInvFIt)
853     removeEntity(*anInvFIt);
854 }
855
856 EntityWrapperPtr SketchSolver_Storage::getNormal() const
857 {
858   EntityWrapperPtr aSketch = sketch();
859   if (!aSketch)
860     return aSketch;
861
862   // Find normal entity
863   const std::list<EntityWrapperPtr>& aSketchSubs = aSketch->subEntities();
864   std::list<EntityWrapperPtr>::const_iterator aSIt = aSketchSubs.begin();
865   for (; aSIt != aSketchSubs.end(); ++aSIt)
866     if ((*aSIt)->type() == ENTITY_NORMAL)
867       return *aSIt;
868   return EntityWrapperPtr();
869 }
870
871 const EntityWrapperPtr& SketchSolver_Storage::sketch() const
872 {
873   static EntityWrapperPtr aDummySketch;
874
875   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator aFIt = myFeatureMap.begin();
876   for (; aFIt != myFeatureMap.end(); ++aFIt)
877     if (aFIt->second && aFIt->second->type() == ENTITY_SKETCH)
878       break;
879   if (aFIt == myFeatureMap.end())
880     return aDummySketch;
881   return aFIt->second;
882 }
883
884 void SketchSolver_Storage::setSketch(const EntityWrapperPtr& theSketch)
885 {
886   if (sketch())
887     return;
888   addEntity(FeaturePtr(), theSketch);
889 }
890
891 void SketchSolver_Storage::processArcs()
892 {
893   myExistArc = false;
894   std::map<FeaturePtr, EntityWrapperPtr>::iterator aFIt = myFeatureMap.begin();
895   for (; aFIt != myFeatureMap.end(); ++aFIt)
896     if (!aFIt->second && aFIt->first->getKind() == SketchPlugin_Arc::ID()) {
897       // Additional checking the attributes are initialized
898       if (aFIt->first->attribute(SketchPlugin_Arc::CENTER_ID())->isInitialized() &&
899           aFIt->first->attribute(SketchPlugin_Arc::START_ID())->isInitialized() &&
900           aFIt->first->attribute(SketchPlugin_Arc::END_ID())->isInitialized())
901         update(aFIt->first);
902       else
903         myExistArc = true;
904     }
905 }
906
907 void SketchSolver_Storage::blockEvents(bool isBlocked)
908 {
909   if (isBlocked == myEventsBlocked)
910     return;
911
912   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
913       aCIter = myConstraintMap.begin();
914   for (; aCIter != myConstraintMap.end(); aCIter++)
915     if (aCIter->first->data() && aCIter->first->data()->isValid())
916       aCIter->first->data()->blockSendAttributeUpdated(isBlocked);
917
918   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator aFIter = myFeatureMap.begin();
919   for (; aFIter != myFeatureMap.end(); aFIter++)
920     if (aFIter->first->data() && aFIter->first->data()->isValid())
921       aFIter->first->data()->blockSendAttributeUpdated(isBlocked);
922
923   std::map<AttributePtr, EntityWrapperPtr>::const_iterator anAtIter = myAttributeMap.begin();
924   for (; anAtIter != myAttributeMap.end(); anAtIter++)
925     if (anAtIter->first->owner() && anAtIter->first->owner()->data() &&
926         anAtIter->first->owner()->data()->isValid())
927       anAtIter->first->owner()->data()->blockSendAttributeUpdated(isBlocked);
928   myEventsBlocked = isBlocked;
929 }
930
931 std::set<ObjectPtr> SketchSolver_Storage::getConflictingConstraints(SolverPtr theSolver) const
932 {
933   std::set<ObjectPtr> aConflicting;
934   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
935       aConstrIt = myConstraintMap.begin();
936   for (; aConstrIt != myConstraintMap.end(); ++aConstrIt) {
937     std::list<ConstraintWrapperPtr>::const_iterator anIt = aConstrIt->second.begin();
938     for (; anIt != aConstrIt->second.end(); ++anIt)
939       if (theSolver->isConflicting((*anIt)->id())) {
940         aConflicting.insert(aConstrIt->first);
941         break;
942       }
943   }
944   return aConflicting;
945 }
946
947
948
949
950
951 // ==============   Auxiliary functions   ====================================
952 bool isEqual(const std::list<ConstraintWrapperPtr>& theCVec1,
953              const std::list<ConstraintWrapperPtr>& theCVec2)
954 {
955   if (theCVec1.size() != theCVec2.size())
956     return false;
957
958   std::list<bool> aChecked(theCVec2.size(), false);
959   std::list<ConstraintWrapperPtr>::const_iterator anIt1 = theCVec1.begin();
960   for (; anIt1 != theCVec1.end(); ++anIt1) {
961     std::list<ConstraintWrapperPtr>::const_iterator anIt2 = theCVec2.begin();
962     std::list<bool>::iterator aCheckIt = aChecked.begin();
963     while (aCheckIt != aChecked.end() && *aCheckIt) {
964       ++aCheckIt;
965       ++anIt2;
966     }
967     for (; anIt2 != theCVec2.end(); ++anIt2, ++aCheckIt)
968       if (!(*aCheckIt) && (*anIt1)->isEqual(*anIt2)) {
969         *aCheckIt = true;
970         break;
971       }
972     // the same constraint is not found
973     if (anIt2 == theCVec2.end())
974       return false;
975   }
976   return true;
977 }
978
979 void resultToFeatureOrAttribute(const ObjectPtr& theResult,
980     FeaturePtr& theFeature, AttributePtr& theAttribute)
981 {
982   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
983   // if the feature has several results, we choose which one is referred
984   const std::list<ResultPtr>& aResults = aFeature->results();
985   if (aResults.size() > 1 && theResult != aFeature->lastResult()) {
986     // actually, the attribute refers to center of arc or circle,
987     // but not the edge, get correct attributes
988     std::string anAttrName;
989     if (aFeature->getKind() == SketchPlugin_Arc::ID())
990       anAttrName = SketchPlugin_Arc::CENTER_ID();
991     else if (aFeature->getKind() == SketchPlugin_Circle::ID())
992       anAttrName = SketchPlugin_Circle::CENTER_ID();
993     if (!anAttrName.empty()) {
994       theAttribute = aFeature->attribute(anAttrName);
995       aFeature = FeaturePtr();
996     }
997   }
998   theFeature = aFeature;
999 }