Salome HOME
e7b72775d3adbaa1a09a8fb8a8fa42287eeefef7
[modules/shaper.git] / src / SketchSolver / SolveSpaceSolver / SolveSpaceSolver_Storage.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SolveSpaceSolver_Storage.cpp
4 // Created: 18 Mar 2015
5 // Author:  Artem ZHIDKOV
6
7 #include <SolveSpaceSolver_Storage.h>
8 #include <SolveSpaceSolver_ConstraintWrapper.h>
9 #include <SolveSpaceSolver_EntityWrapper.h>
10 #include <SolveSpaceSolver_ParameterWrapper.h>
11 #include <SolveSpaceSolver_Builder.h>
12
13 #include <GeomAPI_Dir2d.h>
14 #include <GeomAPI_Pnt2d.h>
15 #include <GeomAPI_XY.h>
16 #include <math.h>
17 #include <assert.h>
18
19 #include <GeomDataAPI_Point.h>
20 #include <GeomDataAPI_Point2D.h>
21 #include <ModelAPI_AttributeDouble.h>
22 #include <ModelAPI_AttributeRefAttr.h>
23 #include <SketchPlugin_Arc.h>
24 #include <SketchPlugin_ConstraintCoincidence.h>
25
26 /** \brief Search the entity/parameter with specified ID in the list of elements
27  *  \param[in] theEntityID unique ID of the element
28  *  \param[in] theEntities list of elements
29  *  \return position of the found element or -1 if the element is not found
30  */
31 template<typename T>
32 static int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities);
33
34 /// \brief Compare two parameters to be different
35 static bool IsNotEqual(const Slvs_Param& theParam1, const Slvs_Param& theParam2);
36 /// \brief Compare two entities to be different
37 static bool IsNotEqual(const Slvs_Entity& theEntity1, const Slvs_Entity& theEntity2);
38 /// \brief Compare two constraints to be different
39 static bool IsNotEqual(const Slvs_Constraint& theConstraint1, const Slvs_Constraint& theConstraint2);
40
41
42 SolveSpaceSolver_Storage::SolveSpaceSolver_Storage(const GroupID& theGroup)
43   : SketchSolver_Storage(theGroup),
44     myWorkplaneID(SLVS_E_UNKNOWN),
45     myParamMaxID(SLVS_E_UNKNOWN),
46     myEntityMaxID(SLVS_E_UNKNOWN),
47     myConstrMaxID(SLVS_C_UNKNOWN),
48     myDuplicatedConstraint(false)
49 {
50 }
51
52 bool SolveSpaceSolver_Storage::update(ConstraintWrapperPtr theConstraint)
53 {
54   bool isUpdated = false;
55   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
56       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
57   Slvs_Constraint aSlvsConstr = getConstraint((Slvs_hConstraint)aConstraint->id());
58   if (aSlvsConstr.h == SLVS_C_UNKNOWN)
59     aSlvsConstr = aConstraint->constraint();
60
61   // update value of constraint if exist
62   double aCoeff = aSlvsConstr.type == SLVS_C_DIAMETER ? 2.0 : 1.0;
63   if (fabs(aSlvsConstr.valA - theConstraint->value() * aCoeff) > tolerance) {
64     aSlvsConstr.valA = theConstraint->value() * aCoeff;
65     isUpdated = true;
66   }
67
68   // update constrained entities
69   Slvs_hEntity* aPnts[2] = {&aSlvsConstr.ptA, &aSlvsConstr.ptB};
70   Slvs_hEntity* anEnts[4] = {&aSlvsConstr.entityA, &aSlvsConstr.entityB,
71                              &aSlvsConstr.entityC, &aSlvsConstr.entityD};
72   int aPtInd = 0;
73   int aEntInd = 0;
74
75   std::list<EntityWrapperPtr> anEntities = theConstraint->entities();
76   std::list<EntityWrapperPtr>::iterator anIt = anEntities.begin();
77   for (; anIt != anEntities.end(); ++anIt) {
78     isUpdated = update(*anIt) || isUpdated;
79     // do not update constrained entities for Multi constraints
80     if (aSlvsConstr.type == SLVS_C_MULTI_ROTATION || aSlvsConstr.type == SLVS_C_MULTI_TRANSLATION)
81       continue;
82
83     Slvs_hEntity anID = (Slvs_hEntity)(*anIt)->id();
84     if ((*anIt)->type() == ENTITY_POINT) {
85       if (*(aPnts[aPtInd]) != anID) {
86         *(aPnts[aPtInd]) = anID;
87         isUpdated = true;
88       }
89       ++aPtInd;
90     } else {
91       if (*(anEnts[aEntInd]) != anID) {
92         *(anEnts[aEntInd]) = anID;
93         isUpdated = true;
94       }
95       ++aEntInd;
96     }
97   }
98
99   // update constraint itself (do not update constraints Multi)
100   if (aSlvsConstr.type != SLVS_C_MULTI_ROTATION && aSlvsConstr.type != SLVS_C_MULTI_TRANSLATION) {
101     if (aSlvsConstr.wrkpl == SLVS_E_UNKNOWN && myWorkplaneID != SLVS_E_UNKNOWN)
102       aSlvsConstr.wrkpl = myWorkplaneID;
103     if (aSlvsConstr.group == SLVS_G_UNKNOWN)
104       aSlvsConstr.group = (Slvs_hGroup)myGroupID;
105     bool hasDupConstraints = myDuplicatedConstraint;
106     Slvs_hConstraint aConstrID = updateConstraint(aSlvsConstr);
107     if (aSlvsConstr.h == SLVS_C_UNKNOWN) {
108       aConstraint->changeConstraint() = getConstraint(aConstrID);
109       isUpdated = true;
110       // check duplicated constraints based on different attributes
111       if (myDuplicatedConstraint && findSameConstraint(aConstraint) && !hasDupConstraints)
112         myDuplicatedConstraint = false;
113     }
114   }
115   return isUpdated;
116 }
117
118 bool SolveSpaceSolver_Storage::update(EntityWrapperPtr theEntity)
119 {
120   bool isUpdated = false;
121   std::shared_ptr<SolveSpaceSolver_EntityWrapper> anEntity = 
122       std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theEntity);
123   Slvs_Entity aSlvsEnt = getEntity((Slvs_hEntity)anEntity->id());
124   if (aSlvsEnt.h == SLVS_E_UNKNOWN)
125     aSlvsEnt = anEntity->entity();
126
127   std::list<ParameterWrapperPtr> aParams = theEntity->parameters();
128   std::list<ParameterWrapperPtr>::iterator aPIt;
129   // if the entity is an attribute, need to update its coordinates
130   if (anEntity->baseAttribute()) {
131     BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
132     EntityWrapperPtr anUpdAttr = aBuilder->createAttribute(anEntity->baseAttribute(), GID_UNKNOWN);
133     if (anUpdAttr) {
134       std::list<ParameterWrapperPtr> anUpdParams = anUpdAttr->parameters();
135       std::list<ParameterWrapperPtr>::iterator anUpdIt = anUpdParams.begin();
136       for (aPIt = aParams.begin(); aPIt != aParams.end() && anUpdIt != anUpdParams.end();
137           ++aPIt, ++anUpdIt) {
138         (*aPIt)->update(*anUpdIt);
139       }
140     }
141   }
142
143   // update parameters
144   int anInd = 0;
145   for (aPIt = aParams.begin(); aPIt != aParams.end(); ++aPIt, ++anInd) {
146     assert(anInd < 4);
147     isUpdated = update(*aPIt) || isUpdated;
148     if (aSlvsEnt.param[anInd] != (Slvs_hEntity)(*aPIt)->id()) {
149       isUpdated = true;
150       aSlvsEnt.param[anInd] = (Slvs_hEntity)(*aPIt)->id();
151     }
152   }
153
154   // update sub-entities
155   std::list<EntityWrapperPtr> aSubEntities = theEntity->subEntities();
156   std::list<EntityWrapperPtr>::iterator aSIt = aSubEntities.begin();
157   for (anInd = 0; aSIt != aSubEntities.end(); ++aSIt, ++anInd) {
158     assert(anInd < 4);
159     isUpdated = update(*aSIt) || isUpdated;
160
161     Slvs_hEntity anID = Slvs_hEntity((*aSIt)->id());
162     if ((*aSIt)->type() == ENTITY_NORMAL)
163       aSlvsEnt.normal = anID;
164     else if ((*aSIt)->type() == ENTITY_SCALAR)
165       aSlvsEnt.distance = anID;
166     else if (aSlvsEnt.point[anInd] != anID) {
167       aSlvsEnt.point[anInd] = anID;
168       if ((*aSIt)->baseAttribute())
169         SketchSolver_Storage::addEntity((*aSIt)->baseAttribute(), *aSIt);
170       isUpdated = true;
171     }
172   }
173   if (theEntity->type() == ENTITY_POINT && aSubEntities.size() == 1) {
174     // theEntity is based on SketchPlugin_Point => need to substitute its attribute instead
175     bool isNew = (aSlvsEnt.h == SLVS_E_UNKNOWN);
176     aSlvsEnt = getEntity(aSlvsEnt.point[0]);
177     if (isNew) {
178       anEntity->changeEntity() = aSlvsEnt;
179       isUpdated = true;
180     }
181   }
182
183   // update entity itself
184   if (aSlvsEnt.wrkpl == SLVS_E_UNKNOWN && myWorkplaneID != SLVS_E_UNKNOWN)
185     aSlvsEnt.wrkpl = myWorkplaneID;
186   if (aSlvsEnt.group == SLVS_G_UNKNOWN)
187     aSlvsEnt.group = (Slvs_hGroup)myGroupID;
188   Slvs_hEntity anEntID = updateEntity(aSlvsEnt);
189   if (aSlvsEnt.h == SLVS_E_UNKNOWN || isUpdated) {
190     anEntity->changeEntity() = getEntity(anEntID);
191     isUpdated = true;
192
193     if (anEntity->type() == ENTITY_SKETCH)
194       storeWorkplane(anEntity);
195   }
196
197   return isUpdated;
198 }
199
200 bool SolveSpaceSolver_Storage::update(ParameterWrapperPtr theParameter)
201 {
202   std::shared_ptr<SolveSpaceSolver_ParameterWrapper> aParameter = 
203       std::dynamic_pointer_cast<SolveSpaceSolver_ParameterWrapper>(theParameter);
204   const Slvs_Param& aParam = getParameter((Slvs_hParam)aParameter->id());
205   if (aParam.h != SLVS_E_UNKNOWN && fabs(aParam.val - aParameter->value()) < tolerance)
206     return false;
207   Slvs_Param aParamToUpd = aParameter->parameter();
208   if (aParamToUpd.group == SLVS_G_UNKNOWN)
209     aParamToUpd.group = aParameter->isParametric() ? (Slvs_hGroup)GID_OUTOFGROUP : (Slvs_hGroup)myGroupID;
210   Slvs_hParam anID = updateParameter(aParamToUpd);
211   if (aParam.h == SLVS_E_UNKNOWN) // new parameter
212     aParameter->changeParameter() = getParameter(anID);
213   return true;
214 }
215
216 void SolveSpaceSolver_Storage::storeWorkplane(EntityWrapperPtr theSketch)
217 {
218   myWorkplaneID = (Slvs_hEntity)theSketch->id();
219
220   // Update sub-entities of the sketch
221   std::list<EntityWrapperPtr> aSubEntities = theSketch->subEntities();
222   std::list<EntityWrapperPtr>::iterator aSIt = aSubEntities.begin();
223   for (; aSIt != aSubEntities.end(); ++aSIt) {
224     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aSub =
225         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*aSIt);
226     aSub->changeEntity().wrkpl = myWorkplaneID;
227   }
228
229   // Update all stored entities
230   std::vector<Slvs_Entity>::iterator anIt = myEntities.begin();
231   for (; anIt != myEntities.end(); ++anIt)
232     anIt->wrkpl = myWorkplaneID;
233 }
234
235 void SolveSpaceSolver_Storage::changeGroup(EntityWrapperPtr theEntity, const GroupID& theGroup)
236 {
237   std::list<ParameterWrapperPtr> aParams = theEntity->parameters();
238   std::list<ParameterWrapperPtr>::iterator aPIt = aParams.begin();
239   for (; aPIt != aParams.end(); ++aPIt)
240     changeGroup(*aPIt, theGroup);
241
242   std::list<EntityWrapperPtr> aSubs = theEntity->subEntities();
243   std::list<EntityWrapperPtr>::iterator aSIt = aSubs.begin();
244   for (; aSIt != aSubs.end(); ++aSIt)
245     changeGroup(*aSIt, theGroup);
246
247   if (theEntity->group() != theGroup) {
248     theEntity->setGroup(theGroup);
249     int aPos = Search((Slvs_hEntity)theEntity->id(), myEntities);
250     if (aPos >= 0 && aPos < (int)myEntities.size()) {
251       myEntities[aPos].group = (Slvs_hGroup)theGroup;
252       setNeedToResolve(true);
253     }
254   }
255 }
256
257 void SolveSpaceSolver_Storage::changeGroup(ParameterWrapperPtr theParam, const GroupID& theGroup)
258 {
259   GroupID aGroup = theGroup;
260   if (theParam->isParametric())
261     aGroup = GID_OUTOFGROUP;
262   if (theParam->group() == aGroup)
263     return;
264
265   theParam->setGroup(aGroup);
266   int aPos = Search((Slvs_hParam)theParam->id(), myParameters);
267   if (aPos >= 0 && aPos < (int)myParameters.size()) {
268     myParameters[aPos].group = (Slvs_hGroup)aGroup;
269     setNeedToResolve(true);
270   }
271 }
272
273 void SolveSpaceSolver_Storage::addCoincidentPoints(
274     EntityWrapperPtr theMaster, EntityWrapperPtr theSlave)
275 {
276   if (theMaster->type() != ENTITY_POINT || theSlave->type() != ENTITY_POINT)
277     return;
278   if (!theMaster->subEntities().empty() || !theSlave->subEntities().empty()) {
279     EntityWrapperPtr aSubMaster = theMaster->subEntities().empty() ?
280         theMaster : theMaster->subEntities().front();
281     EntityWrapperPtr aSubSlave = theSlave->subEntities().empty() ?
282         theSlave : theSlave->subEntities().front();
283     return addCoincidentPoints(aSubMaster, aSubSlave);
284   }
285
286   // Search available coincidence
287   CoincidentPointsMap::iterator aMasterFound = myCoincidentPoints.find(theMaster);
288   CoincidentPointsMap::iterator aSlaveFound = myCoincidentPoints.find(theSlave);
289   if (aMasterFound == myCoincidentPoints.end() || aSlaveFound == myCoincidentPoints.end()) {
290     // try to find master and slave points in the lists of slaves of already existent coincidences
291     CoincidentPointsMap::iterator anIt = myCoincidentPoints.begin();
292     for (; anIt != myCoincidentPoints.end(); ++anIt) {
293       if (anIt->second.find(theMaster) != anIt->second.end())
294         aMasterFound = anIt;
295       else if (anIt->second.find(theSlave) != anIt->second.end())
296         aSlaveFound = anIt;
297
298       if (aMasterFound != myCoincidentPoints.end() &&  aSlaveFound != myCoincidentPoints.end())
299         break;
300     }
301   }
302
303   if (aMasterFound == myCoincidentPoints.end()) {
304     // create new group
305     myCoincidentPoints[theMaster] = std::set<EntityWrapperPtr>();
306     aMasterFound = myCoincidentPoints.find(theMaster);
307   } else if (aMasterFound == aSlaveFound)
308     return; // already coincident
309
310   if (aSlaveFound != myCoincidentPoints.end()) {
311     // A slave has been found, we need to attach all points coincident with it to the new master
312     std::set<EntityWrapperPtr> aNewSlaves = aSlaveFound->second;
313     aNewSlaves.insert(aSlaveFound->first);
314     myCoincidentPoints.erase(aSlaveFound);
315
316     std::set<EntityWrapperPtr>::const_iterator aSlIt = aNewSlaves.begin();
317     for (; aSlIt != aNewSlaves.end(); ++aSlIt)
318       addCoincidentPoints(theMaster, *aSlIt);
319   } else {
320     // Update the slave if it was used in constraints and features
321     replaceInFeatures(theSlave, theMaster);
322     replaceInConstraints(theSlave, theMaster);
323
324     // Remove slave entity (if the IDs are equal no need to remove slave entity, just update it)
325     if (theMaster->id() != theSlave->id())
326       removeEntity((Slvs_hEntity)theSlave->id());
327
328     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aPointMaster = 
329         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theMaster);
330     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aPointSlave = 
331         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theSlave);
332     aPointSlave->changeEntity() = aPointMaster->entity();
333     aPointSlave->setParameters(aPointMaster->parameters());
334
335     aMasterFound->second.insert(theSlave);
336   }
337 }
338
339 void SolveSpaceSolver_Storage::replaceInFeatures(
340     EntityWrapperPtr theSource, EntityWrapperPtr theDest)
341 {
342   std::map<FeaturePtr, EntityWrapperPtr>::const_iterator anIt = myFeatureMap.begin();
343   for (; anIt != myFeatureMap.end(); ++anIt) {
344     if (!anIt->second)
345       continue;
346     bool isUpdated = false;
347     std::list<EntityWrapperPtr> aSubs = anIt->second->subEntities();
348     std::list<EntityWrapperPtr>::iterator aSubIt = aSubs.begin();
349     for (; aSubIt != aSubs.end(); ++aSubIt)
350       if ((*aSubIt)->id() == theSource->id()) {
351         (*aSubIt)->update(theDest);
352         isUpdated = true;
353       }
354
355     if (!isUpdated)
356       continue;
357
358     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aWrapper =
359         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(anIt->second);
360     // update SolveSpace entity
361     Slvs_Entity anEnt = aWrapper->entity();
362     for (int i = 0; i < 4; ++i)
363       if (anEnt.point[i] == (Slvs_hEntity)theSource->id())
364         anEnt.point[i] = (Slvs_hEntity)theDest->id();
365     anEnt.h = updateEntity(anEnt);
366     aWrapper->changeEntity() = anEnt;
367
368     // update sub-entities
369     aWrapper->setSubEntities(aSubs);
370   }
371 }
372
373 void SolveSpaceSolver_Storage::replaceInConstraints(
374     EntityWrapperPtr theSource, EntityWrapperPtr theDest)
375 {
376   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
377       anIt = myConstraintMap.begin();
378   std::list<ConstraintWrapperPtr>::const_iterator aCIt;
379   for (; anIt != myConstraintMap.end(); ++anIt)
380     for (aCIt = anIt->second.begin(); aCIt != anIt->second.end(); ++aCIt) {
381       // Do not process coincidence between points and "multi" constraints
382       // (these constraints are stored to keep the structure of constraints).
383       if ((*aCIt)->type() == CONSTRAINT_PT_PT_COINCIDENT ||
384           (*aCIt)->type() == CONSTRAINT_MULTI_ROTATION ||
385           (*aCIt)->type() == CONSTRAINT_MULTI_TRANSLATION)
386         continue;
387
388       bool isUpdated = false;
389       std::list<EntityWrapperPtr> aSubs = (*aCIt)->entities();
390       std::list<EntityWrapperPtr>::iterator aSubIt = aSubs.begin();
391       for (; aSubIt != aSubs.end(); ++aSubIt)
392         if ((*aSubIt)->id() == theSource->id()) {
393           (*aSubIt)->update(theDest);
394           isUpdated = true;
395         }
396
397       if (!isUpdated)
398         continue;
399
400       std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aWrapper =
401           std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(*aCIt);
402       if (theSource->id() == theDest->id()) {
403         // No need to update SolveSpace constraint if the entities are the same
404         aWrapper->changeConstraint() = getConstraint((Slvs_hConstraint)aWrapper->id());
405         aWrapper->setEntities(aSubs);
406         continue;
407       }
408
409       // change constraint entities
410       Slvs_Constraint aConstr = aWrapper->constraint();
411       if (aConstr.ptA == (Slvs_hEntity)theSource->id())
412         aConstr.ptA = (Slvs_hEntity)theDest->id();
413       if (aConstr.ptB == (Slvs_hEntity)theSource->id())
414         aConstr.ptB = (Slvs_hEntity)theDest->id();
415
416       // check the constraint is duplicated
417       std::vector<Slvs_Constraint>::const_iterator aSlvsCIt = myConstraints.begin();
418       for (; aSlvsCIt != myConstraints.end(); ++aSlvsCIt)
419         if (aConstr.h != aSlvsCIt->h &&
420             aConstr.type == aSlvsCIt->type &&
421             aConstr.ptA == aSlvsCIt->ptA && aConstr.ptB == aSlvsCIt->ptB &&
422             aConstr.entityA == aSlvsCIt->entityA && aConstr.entityB == aSlvsCIt->entityB &&
423             aConstr.entityC == aSlvsCIt->entityC && aConstr.entityD == aSlvsCIt->entityD) {
424           Slvs_hConstraint anIDToRemove = aConstr.h;
425           aConstr = *aSlvsCIt;
426           int aShift = (int)(aSlvsCIt - myConstraints.begin());
427           removeConstraint(anIDToRemove);
428           aSlvsCIt = myConstraints.begin() + aShift - 1;
429           for (; aSlvsCIt != myConstraints.end(); ++aSlvsCIt)
430             if (aSlvsCIt->h == aConstr.h)
431               break;
432           break;
433         }
434
435       if (aSlvsCIt != myConstraints.end()) {
436         // constraint is duplicated, search its wrapper to add the mapping
437         std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
438             anIt2 = myConstraintMap.begin();
439         std::list<ConstraintWrapperPtr>::const_iterator aCIt2;
440         for (; anIt2 != myConstraintMap.end(); ++anIt2)
441           for (aCIt2 = anIt2->second.begin(); aCIt2 != anIt2->second.end(); ++aCIt2)
442             if ((Slvs_hConstraint)(*aCIt2)->id() == aConstr.h) {
443               addSameConstraints(*aCIt2, aWrapper);
444               break;
445             }
446       } else 
447         aConstr.h = updateConstraint(aConstr);
448       aWrapper->changeConstraint() = aConstr;
449
450       // update sub-entities
451       aWrapper->setEntities(aSubs);
452     }
453 }
454
455 void SolveSpaceSolver_Storage::addSameConstraints(ConstraintWrapperPtr theConstraint1,
456                                                   ConstraintWrapperPtr theConstraint2)
457 {
458   SameConstraintMap::iterator anIt = myEqualConstraints.begin();
459   for (; anIt != myEqualConstraints.end(); ++anIt) {
460     if (anIt->find(theConstraint1) != anIt->end()) {
461       anIt->insert(theConstraint2);
462       return;
463     }
464     else if (anIt->find(theConstraint2) != anIt->end()) {
465       anIt->insert(theConstraint1);
466       return;
467     }
468   }
469   // group not found => create new one
470   std::set<ConstraintWrapperPtr> aNewGroup;
471   aNewGroup.insert(theConstraint1);
472   aNewGroup.insert(theConstraint2);
473   myEqualConstraints.push_back(aNewGroup);
474 }
475
476 bool SolveSpaceSolver_Storage::findSameConstraint(ConstraintWrapperPtr theConstraint)
477 {
478   if (theConstraint->type() == CONSTRAINT_PT_PT_COINCIDENT ||
479       theConstraint->type() == CONSTRAINT_MULTI_ROTATION ||
480       theConstraint->type() == CONSTRAINT_MULTI_TRANSLATION)
481     return false;
482
483   const Slvs_Constraint& aCBase =
484       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint)->constraint();
485
486   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
487       aCIt = myConstraintMap.begin();
488   std::list<ConstraintWrapperPtr>::const_iterator aCWIt;
489   for (; aCIt != myConstraintMap.end(); ++aCIt)
490     for (aCWIt = aCIt->second.begin(); aCWIt != aCIt->second.end(); ++aCWIt) {
491       if ((*aCWIt)->type() == CONSTRAINT_PT_PT_COINCIDENT ||
492           (*aCWIt)->type() == CONSTRAINT_MULTI_ROTATION ||
493           (*aCWIt)->type() == CONSTRAINT_MULTI_TRANSLATION)
494         continue;
495       if ((*aCWIt)->type() == theConstraint->type()) {
496         const Slvs_Constraint& aCComp = getConstraint((Slvs_hConstraint)(*aCWIt)->id());
497
498         if (aCBase.ptA == aCComp.ptA && aCBase.ptB == aCComp.ptB &&
499             aCBase.entityA == aCComp.entityA && aCBase.entityB == aCComp.entityB &&
500             aCBase.entityC == aCComp.entityC && aCBase.entityD == aCComp.entityD &&
501             fabs(aCBase.valA -aCComp.valA) < tolerance) {
502           addSameConstraints(*aCWIt, theConstraint);
503           return true;
504         }
505       }
506     }
507   return false;
508 }
509
510
511 EntityWrapperPtr SolveSpaceSolver_Storage::calculateMiddlePoint(
512     EntityWrapperPtr theBase, double theCoeff)
513 {
514   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
515
516   std::shared_ptr<GeomAPI_XY> aMidPoint;
517   if (theBase->type() == ENTITY_LINE) {
518     std::shared_ptr<GeomAPI_Pnt2d> aPoints[2];
519     const std::list<EntityWrapperPtr>& aSubs = theBase->subEntities();
520     std::list<EntityWrapperPtr>::const_iterator anIt = aSubs.begin();
521     for (int i = 0; i < 2; ++i, ++anIt)
522       aPoints[i] = aBuilder->point(*anIt);
523     aMidPoint = aPoints[0]->xy()->multiplied(1.0 - theCoeff)->added(
524         aPoints[1]->xy()->multiplied(theCoeff));
525   }
526   else if (theBase->type() == ENTITY_ARC) {
527     double theX, theY;
528     double anArcPoint[3][2];
529     const std::list<EntityWrapperPtr>& aSubs = theBase->subEntities();
530     std::list<EntityWrapperPtr>::const_iterator anIt = aSubs.begin();
531     for (int i = 0; i < 3; ++i, ++anIt) {
532       std::shared_ptr<GeomAPI_Pnt2d> aPoint = aBuilder->point(*anIt);
533       anArcPoint[i][0] = aPoint->x();
534       anArcPoint[i][1] = aPoint->y();
535     }
536     // project last point of arc on the arc
537     double x = anArcPoint[1][0] - anArcPoint[0][0];
538     double y = anArcPoint[1][1] - anArcPoint[0][1];
539     double aRad = sqrt(x*x + y*y);
540     x = anArcPoint[2][0] - anArcPoint[0][0];
541     y = anArcPoint[2][1] - anArcPoint[0][1];
542     double aNorm = sqrt(x*x + y*y);
543     if (aNorm >= tolerance) {
544       anArcPoint[2][0] = x * aRad / aNorm;
545       anArcPoint[2][1] = y * aRad / aNorm;
546     }
547     anArcPoint[1][0] -= anArcPoint[0][0];
548     anArcPoint[1][1] -= anArcPoint[0][1];
549     if (theCoeff < tolerance) {
550       theX = anArcPoint[0][0] + anArcPoint[1][0];
551       theY = anArcPoint[0][1] + anArcPoint[1][1];
552     } else if (1 - theCoeff < tolerance) {
553       theX = anArcPoint[0][0] + anArcPoint[2][0];
554       theY = anArcPoint[0][1] + anArcPoint[2][1];
555     } else {
556       std::shared_ptr<GeomAPI_Dir2d> aStartDir(new GeomAPI_Dir2d(anArcPoint[1][0], anArcPoint[1][1]));
557       std::shared_ptr<GeomAPI_Dir2d> aEndDir(new GeomAPI_Dir2d(anArcPoint[2][0], anArcPoint[2][1]));
558       double anAngle = aStartDir->angle(aEndDir);
559       if (anAngle < 0)
560         anAngle += 2.0 * PI;
561       anAngle *= theCoeff;
562       double aCos = cos(anAngle);
563       double aSin = sin(anAngle);
564       theX = anArcPoint[0][0] + anArcPoint[1][0] * aCos - anArcPoint[1][1] * aSin;
565       theY = anArcPoint[0][1] + anArcPoint[1][0] * aSin + anArcPoint[1][1] * aCos;
566     }
567     aMidPoint = std::shared_ptr<GeomAPI_XY>(new GeomAPI_XY(theX, theY));
568   }
569
570   if (!aMidPoint)
571     return EntityWrapperPtr();
572
573   std::list<ParameterWrapperPtr> aParameters;
574   Slvs_Param aParam1 = Slvs_MakeParam(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID, aMidPoint->x());
575   aParam1.h = addParameter(aParam1);
576   aParameters.push_back(ParameterWrapperPtr(new SolveSpaceSolver_ParameterWrapper(aParam1)));
577   Slvs_Param aParam2 = Slvs_MakeParam(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID, aMidPoint->y());
578   aParam2.h = addParameter(aParam2);
579   aParameters.push_back(ParameterWrapperPtr(new SolveSpaceSolver_ParameterWrapper(aParam2)));
580   // Create entity (parameters are not filled)
581   Slvs_Entity anEntity = Slvs_MakePoint2d(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID,
582       (Slvs_hEntity)myWorkplaneID, aParam1.h, aParam2.h);
583   anEntity.h = addEntity(anEntity);
584
585   EntityWrapperPtr aResult(new SolveSpaceSolver_EntityWrapper(AttributePtr(), anEntity));
586   aResult->setParameters(aParameters);
587   return aResult;
588 }
589
590
591
592
593
594
595 Slvs_hParam SolveSpaceSolver_Storage::addParameter(const Slvs_Param& theParam)
596 {
597   if (theParam.h > 0 && theParam.h <= myParamMaxID) {
598     // parameter is already used, rewrite it
599     return updateParameter(theParam);
600   }
601
602   Slvs_Param aParam = theParam;
603   if (aParam.h > myParamMaxID)
604     myParamMaxID = aParam.h;
605   else
606     aParam.h = ++myParamMaxID;
607   myParameters.push_back(aParam);
608   myNeedToResolve = true;
609   return aParam.h;
610 }
611
612 Slvs_hParam SolveSpaceSolver_Storage::updateParameter(const Slvs_Param& theParam)
613 {
614   if (theParam.h > 0 && theParam.h <= myParamMaxID) {
615     // parameter already used, rewrite it
616     int aPos = Search(theParam.h, myParameters);
617     if (aPos >= 0 && aPos < (int)myParameters.size()) {
618       if (IsNotEqual(myParameters[aPos], theParam))
619         setNeedToResolve(true);
620       myParameters[aPos] = theParam;
621       return theParam.h;
622     }
623   }
624
625   // Parameter is not found, add new one
626   Slvs_Param aParam = theParam;
627   aParam.h = 0;
628   return addParameter(aParam);
629 }
630
631 bool SolveSpaceSolver_Storage::removeParameter(const Slvs_hParam& theParamID)
632 {
633   int aPos = Search(theParamID, myParameters);
634   if (aPos >= 0 && aPos < (int)myParameters.size()) {
635     // Firstly, search the parameter is not used elsewhere
636     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
637     for (; anEntIter != myEntities.end(); anEntIter++) {
638       for (int i = 0; i < 4; i++)
639         if (anEntIter->param[i] == theParamID)
640           return false;
641     }
642     // Remove parameter
643     myParameters.erase(myParameters.begin() + aPos);
644     myParamMaxID = myParameters.empty() ? SLVS_E_UNKNOWN : myParameters.back().h;
645     myNeedToResolve = true;
646   }
647   return true;
648 }
649
650 const Slvs_Param& SolveSpaceSolver_Storage::getParameter(const Slvs_hParam& theParamID) const
651 {
652   int aPos = Search(theParamID, myParameters);
653   if (aPos >= 0 && aPos < (int)myParameters.size())
654     return myParameters[aPos];
655
656   // Parameter is not found, return empty object
657   static Slvs_Param aDummy;
658   aDummy.h = 0;
659   return aDummy;
660 }
661
662
663 Slvs_hEntity SolveSpaceSolver_Storage::addEntity(const Slvs_Entity& theEntity)
664 {
665   if (theEntity.h > 0 && theEntity.h <= myEntityMaxID) {
666     // Entity is already used, rewrite it
667     return updateEntity(theEntity);
668   }
669
670   Slvs_Entity aEntity = theEntity;
671   if (aEntity.h > myEntityMaxID)
672     myEntityMaxID = aEntity.h;
673   else
674     aEntity.h = ++myEntityMaxID;
675   myEntities.push_back(aEntity);
676   myNeedToResolve = true;
677   return aEntity.h;
678 }
679
680 Slvs_hEntity SolveSpaceSolver_Storage::updateEntity(const Slvs_Entity& theEntity)
681 {
682   if (theEntity.h > 0 && theEntity.h <= myEntityMaxID) {
683     // Entity already used, rewrite it
684     int aPos = Search(theEntity.h, myEntities);
685     if (aPos >= 0 && aPos < (int)myEntities.size()) {
686       myNeedToResolve = myNeedToResolve || IsNotEqual(myEntities[aPos], theEntity);
687       myEntities[aPos] = theEntity;
688       return theEntity.h;
689     }
690   }
691
692   // Entity is not found, add new one
693   Slvs_Entity aEntity = theEntity;
694   aEntity.h = 0;
695   return addEntity(aEntity);
696 }
697
698 bool SolveSpaceSolver_Storage::removeEntity(const Slvs_hEntity& theEntityID)
699 {
700   bool aResult = true;
701   int aPos = Search(theEntityID, myEntities);
702   if (aPos >= 0 && aPos < (int)myEntities.size()) {
703     // Firstly, check the entity and its attributes is not used elsewhere
704     std::set<Slvs_hEntity> anEntAndSubs;
705     anEntAndSubs.insert(theEntityID);
706     for (int i = 0; i < 4; i++)
707       if (myEntities[aPos].point[i] != SLVS_E_UNKNOWN)
708         anEntAndSubs.insert(myEntities[aPos].point[i]);
709
710     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
711     for (; anEntIter != myEntities.end(); anEntIter++) {
712       if (anEntAndSubs.find(anEntIter->h) != anEntAndSubs.end())
713         continue;
714       for (int i = 0; i < 4; i++)
715         if (anEntAndSubs.find(anEntIter->point[i]) != anEntAndSubs.end())
716           return false;
717       if (anEntAndSubs.find(anEntIter->distance) != anEntAndSubs.end())
718         return false;
719     }
720     std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
721     for (; aConstrIter != myConstraints.end(); aConstrIter++) {
722       Slvs_hEntity anEntIDs[6] = {aConstrIter->ptA, aConstrIter->ptB,
723           aConstrIter->entityA, aConstrIter->entityB,
724           aConstrIter->entityC, aConstrIter->entityD};
725       for (int i = 0; i < 6; i++)
726         if (anEntAndSubs.find(anEntIDs[i]) != anEntAndSubs.end())
727           return false;
728     }
729     // The entity is not used, remove it and its parameters
730     Slvs_Entity anEntity = myEntities[aPos];
731     myEntities.erase(myEntities.begin() + aPos);
732     myEntityMaxID = myEntities.empty() ? SLVS_E_UNKNOWN : myEntities.back().h;
733     if (anEntity.distance != SLVS_E_UNKNOWN)
734       aResult = aResult && removeParameter(anEntity.distance);
735     for (int i = 0; i < 4; i++)
736       if (anEntity.param[i] != SLVS_E_UNKNOWN)
737         aResult = removeParameter(anEntity.param[i]) && aResult;
738     myNeedToResolve = true;
739   }
740   return aResult;
741 }
742
743 const Slvs_Entity& SolveSpaceSolver_Storage::getEntity(const Slvs_hEntity& theEntityID) const
744 {
745   int aPos = Search(theEntityID, myEntities);
746   if (aPos >= 0 && aPos < (int)myEntities.size())
747     return myEntities[aPos];
748
749   // Entity is not found, return empty object
750   static Slvs_Entity aDummy;
751   aDummy.h = SLVS_E_UNKNOWN;
752   return aDummy;
753 }
754
755
756 Slvs_hConstraint SolveSpaceSolver_Storage::addConstraint(const Slvs_Constraint& theConstraint)
757 {
758   if (theConstraint.h > 0 && theConstraint.h <= myConstrMaxID) {
759     // Constraint is already used, rewrite it
760     return updateConstraint(theConstraint);
761   }
762
763   Slvs_Constraint aConstraint = theConstraint;
764
765   // Find a constraint with same type uses same arguments to show user overconstraint situation
766   std::vector<Slvs_Constraint>::iterator aCIt = myConstraints.begin();
767   for (; aCIt != myConstraints.end(); aCIt++) {
768     if (aConstraint.type != aCIt->type)
769       continue;
770     if (aConstraint.ptA == aCIt->ptA && aConstraint.ptB == aCIt->ptB &&
771         aConstraint.entityA == aCIt->entityA && aConstraint.entityB == aCIt->entityB &&
772         aConstraint.entityC == aCIt->entityC && aConstraint.entityD == aCIt->entityD) {
773       myDuplicatedConstraint = true;
774       break;
775     }
776   }
777
778   if (aConstraint.h > myConstrMaxID)
779     myConstrMaxID = aConstraint.h;
780   else
781     aConstraint.h = ++myConstrMaxID;
782   myConstraints.push_back(aConstraint);
783   myNeedToResolve = true;
784   return aConstraint.h;
785 }
786
787 Slvs_hConstraint SolveSpaceSolver_Storage::updateConstraint(const Slvs_Constraint& theConstraint)
788 {
789   if (theConstraint.h > 0 && theConstraint.h <= myConstrMaxID) {
790     // Constraint already used, rewrite it
791     int aPos = Search(theConstraint.h, myConstraints);
792     if (aPos >= 0 && aPos < (int)myConstraints.size()) {
793       myNeedToResolve = myNeedToResolve || IsNotEqual(myConstraints[aPos], theConstraint);
794       myConstraints[aPos] = theConstraint;
795       return theConstraint.h;
796     }
797   }
798
799   // Constraint is not found, add new one
800   Slvs_Constraint aConstraint = theConstraint;
801   aConstraint.h = 0;
802
803   // Firstly, check middle-point constraint conflicts with point-on-line
804   if (aConstraint.type == SLVS_C_AT_MIDPOINT) {
805     std::vector<Slvs_Constraint>::const_iterator anIt = myConstraints.begin();
806     for (; anIt != myConstraints.end(); ++anIt)
807       if (anIt->type == SLVS_C_PT_ON_LINE &&
808           anIt->ptA == aConstraint.ptA &&
809           anIt->entityA == aConstraint.entityA)
810         break;
811     if (anIt != myConstraints.end()) {
812       // change the constraint to the lengths equality to avoid conflicts
813       Slvs_Entity aLine = getEntity(aConstraint.entityA);
814       Slvs_Entity aNewLine1 = Slvs_MakeLineSegment(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID,
815           myWorkplaneID, aLine.point[0], aConstraint.ptA);
816       aNewLine1.h = addEntity(aNewLine1);
817       Slvs_Entity aNewLine2 = Slvs_MakeLineSegment(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID,
818           myWorkplaneID, aLine.point[1], aConstraint.ptA);
819       aNewLine2.h = addEntity(aNewLine2);
820       aConstraint = Slvs_MakeConstraint(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID, SLVS_C_EQUAL_LENGTH_LINES,
821           myWorkplaneID, 0.0, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, aNewLine1.h, aNewLine2.h);
822     }
823   }
824
825   return addConstraint(aConstraint);
826 }
827
828 bool SolveSpaceSolver_Storage::removeConstraint(const Slvs_hConstraint& theConstraintID)
829 {
830   int aPos = Search(theConstraintID, myConstraints);
831   if (aPos >= 0 && aPos < (int)myConstraints.size()) {
832     Slvs_Constraint aConstraint = myConstraints[aPos];
833     myConstraints.erase(myConstraints.begin() + aPos);
834     myConstrMaxID = myConstraints.empty() ? SLVS_E_UNKNOWN : myConstraints.back().h;
835     myNeedToResolve = true;
836
837     if (myDuplicatedConstraint) {
838       // Find a constraint with same type uses same arguments
839       std::vector<Slvs_Constraint>::iterator aCIt = myConstraints.begin();
840       for (; aCIt != myConstraints.end(); aCIt++) {
841         if (aConstraint.type != aCIt->type)
842           continue;
843         if (aConstraint.ptA == aCIt->ptA && aConstraint.ptB == aCIt->ptB &&
844             aConstraint.entityA == aCIt->entityA && aConstraint.entityB == aCIt->entityB &&
845             aConstraint.entityC == aCIt->entityC && aConstraint.entityD == aCIt->entityD) {
846           myDuplicatedConstraint = false;
847           break;
848         }
849       }
850     }
851   }
852   return true;
853 }
854
855 const Slvs_Constraint& SolveSpaceSolver_Storage::getConstraint(const Slvs_hConstraint& theConstraintID) const
856 {
857   int aPos = Search(theConstraintID, myConstraints);
858   if (aPos >= 0 && aPos < (int)myConstraints.size())
859     return myConstraints[aPos];
860
861   // Constraint is not found, return empty object
862   static Slvs_Constraint aDummy;
863   aDummy.h = 0;
864   return aDummy;
865 }
866
867
868 void SolveSpaceSolver_Storage::initializeSolver(SolverPtr theSolver)
869 {
870   std::shared_ptr<SolveSpaceSolver_Solver> aSolver =
871       std::dynamic_pointer_cast<SolveSpaceSolver_Solver>(theSolver);
872   if (!aSolver)
873     return;
874
875   if (myExistArc)
876     processArcs();
877
878   if (myConstraints.empty()) {
879     // Adjust all arc to place their points correctly
880     std::vector<Slvs_Entity>::const_iterator anEntIt = myEntities.begin();
881     for (; anEntIt != myEntities.end(); ++anEntIt)
882       if (anEntIt->type == SLVS_E_ARC_OF_CIRCLE)
883         adjustArc(*anEntIt);
884   }
885
886   aSolver->setParameters(myParameters.data(), (int)myParameters.size());
887   aSolver->setEntities(myEntities.data(), (int)myEntities.size());
888   aSolver->setConstraints(myConstraints.data(), (int)myConstraints.size());
889 }
890
891
892 bool SolveSpaceSolver_Storage::removeCoincidence(ConstraintWrapperPtr theConstraint)
893 {
894   std::list<EntityWrapperPtr> aPoints = theConstraint->entities();
895   std::list<EntityWrapperPtr>::const_iterator aPIt;
896
897   CoincidentPointsMap::iterator aPtPtIt = myCoincidentPoints.begin();
898   for (; aPtPtIt != myCoincidentPoints.end(); ++aPtPtIt) {
899     for (aPIt = aPoints.begin(); aPIt != aPoints.end(); ++aPIt)
900       if (aPtPtIt->first == *aPIt ||
901           aPtPtIt->second.find(*aPIt) != aPtPtIt->second.end())
902         break;
903     if (aPIt != aPoints.end())
904       break;
905   }
906
907   if (aPtPtIt == myCoincidentPoints.end())
908     return true; // already removed
909
910   // Create new copies of coincident points
911   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
912   std::list<EntityWrapperPtr> aNewPoints;
913   for (aPIt = aPoints.begin(); aPIt != aPoints.end(); ++aPIt)
914     aNewPoints.push_back(aBuilder->createAttribute(
915         (*aPIt)->baseAttribute(), myGroupID, myWorkplaneID));
916
917   // Find all points fallen out of group of coincident points
918   std::map<EntityWrapperPtr, EntityWrapperPtr> aNotCoinc;
919   aNotCoinc[aPtPtIt->first] = EntityWrapperPtr();
920   std::set<EntityWrapperPtr>::const_iterator aTempIt = aPtPtIt->second.begin();
921   for (; aTempIt != aPtPtIt->second.end(); ++aTempIt)
922     aNotCoinc[*aTempIt] = EntityWrapperPtr();
923   std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::iterator
924       aConstrIt = myConstraintMap.begin();
925   for (; aConstrIt != myConstraintMap.end(); ++aConstrIt)
926     if (aConstrIt->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
927       AttributeRefAttrPtr aRefAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
928           aConstrIt->first->attribute(SketchPlugin_Constraint::ENTITY_A()));
929       AttributeRefAttrPtr aRefAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
930           aConstrIt->first->attribute(SketchPlugin_Constraint::ENTITY_B()));
931       if (!aRefAttrA || !aRefAttrB || aRefAttrA->isObject() || aRefAttrB->isObject())
932         continue;
933       std::map<AttributePtr, EntityWrapperPtr>::iterator
934           aFound = myAttributeMap.find(aRefAttrA->attr());
935       if (aFound != myAttributeMap.end())
936         aNotCoinc.erase(aFound->second);
937       aFound = myAttributeMap.find(aRefAttrB->attr());
938       if (aFound != myAttributeMap.end())
939         aNotCoinc.erase(aFound->second);
940     }
941   if (aNotCoinc.empty())
942     return false;
943   std::list<EntityWrapperPtr>::const_iterator aNewPIt;
944   for (aPIt = aPoints.begin(), aNewPIt = aNewPoints.begin();
945        aPIt != aPoints.end(); ++aPIt, ++aNewPIt) {
946     if (aNotCoinc.find(*aPIt) != aNotCoinc.end())
947       aNotCoinc[*aPIt] = *aNewPIt;
948   }
949
950   // Find all features and constraints uses coincident points
951   std::map<EntityWrapperPtr, EntityWrapperPtr>::iterator aNotCIt;
952   std::set<EntityWrapperPtr> anUpdFeatures;
953   std::map<FeaturePtr, EntityWrapperPtr>::iterator aFIt = myFeatureMap.begin();
954   for (; aFIt != myFeatureMap.end(); ++aFIt) {
955     if (!aFIt->second)
956       continue; // avoid not completed arcs
957     for (aNotCIt = aNotCoinc.begin(); aNotCIt != aNotCoinc.end(); ++aNotCIt) {
958       if (!aNotCIt->second || !aFIt->second->isUsed(aNotCIt->first->baseAttribute()))
959         continue;
960       std::list<EntityWrapperPtr> aSubs = aFIt->second->subEntities();
961       std::list<EntityWrapperPtr>::iterator aSIt = aSubs.begin();
962       bool isUpd = false;
963       for (; aSIt != aSubs.end(); ++aSIt)
964         if (*aSIt == aNotCIt->first) {
965           *aSIt = aNotCIt->second;
966           isUpd = true;
967         }
968       if (isUpd) {
969         aFIt->second->setSubEntities(aSubs);
970         anUpdFeatures.insert(aFIt->second);
971       }
972     }
973   }
974   // update features
975   std::set<EntityWrapperPtr>::iterator anUpdIt = anUpdFeatures.begin();
976   for (; anUpdIt != anUpdFeatures.end(); ++anUpdIt)
977     update(EntityWrapperPtr(*anUpdIt));
978
979   // remove not coincident points
980   for (aNotCIt = aNotCoinc.begin(); aNotCIt != aNotCoinc.end(); ++aNotCIt) {
981     if (aPtPtIt->second.size() <= 1) {
982       myCoincidentPoints.erase(aPtPtIt);
983       break;
984     }
985     if (aPtPtIt->first == aNotCIt->first) {
986       std::set<EntityWrapperPtr> aSlaves = aPtPtIt->second;
987       EntityWrapperPtr aNewMaster = *aSlaves.begin();
988       aSlaves.erase(aSlaves.begin());
989       myCoincidentPoints.erase(aPtPtIt);
990       myCoincidentPoints[aNewMaster] = aSlaves;
991       aPtPtIt = myCoincidentPoints.find(aNewMaster);
992     } else
993       aPtPtIt->second.erase(aNotCIt->first);
994   }
995   return true;
996 }
997
998 bool SolveSpaceSolver_Storage::remove(ConstraintWrapperPtr theConstraint)
999 {
1000   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
1001       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
1002
1003   // verify whether the constraint has duplicated
1004   bool hasSameID = false;
1005   SameConstraintMap::iterator anEqIt = myEqualConstraints.begin();
1006   for (; anEqIt != myEqualConstraints.end(); ++anEqIt) {
1007     std::set<ConstraintWrapperPtr>::const_iterator aFound = anEqIt->find(aConstraint);
1008     if (aFound != anEqIt->end()) {
1009       // verify there is a constraint with same ID
1010       std::set<ConstraintWrapperPtr>::const_iterator anIt = anEqIt->begin();
1011       ConstraintID anID = (*aFound)->id();
1012       for (++anIt; anIt != anEqIt->end() && !hasSameID; ++anIt)
1013         if ((*anIt)->id() == anID && aFound != anIt)
1014           hasSameID = true;
1015       // erase constraint
1016       anEqIt->erase(aConstraint);
1017       break;
1018     }
1019   }
1020   if (anEqIt != myEqualConstraints.end() && hasSameID)
1021     return true;
1022
1023   bool isFullyRemoved = removeConstraint((Slvs_hConstraint)aConstraint->id());
1024   // remove point-point coincidence
1025   if (aConstraint->type() == CONSTRAINT_PT_PT_COINCIDENT)
1026     isFullyRemoved = removeCoincidence(theConstraint) && isFullyRemoved;
1027   return SketchSolver_Storage::remove(theConstraint) && isFullyRemoved;
1028 }
1029
1030 bool SolveSpaceSolver_Storage::remove(EntityWrapperPtr theEntity)
1031 {
1032   if (!theEntity)
1033     return false;
1034
1035   // Additional check for entity to be used in point-point coincidence
1036   bool isCoincide = false;
1037   if (theEntity->type() == ENTITY_POINT) {
1038     CoincidentPointsMap::const_iterator anIt = myCoincidentPoints.begin();
1039     std::set<EntityWrapperPtr>::const_iterator aCIt;
1040     for (; anIt != myCoincidentPoints.end(); ++anIt) {
1041       if (anIt->first == theEntity)
1042         break;
1043       for (aCIt = anIt->second.begin(); aCIt != anIt->second.end(); ++aCIt)
1044         if (*aCIt == theEntity)
1045           break;
1046       if (aCIt != anIt->second.end())
1047         break;
1048     }
1049     if (anIt != myCoincidentPoints.end()) {
1050       if (anIt->first != theEntity && isUsed(anIt->first->baseAttribute()))
1051         isCoincide = true;
1052       for (aCIt = anIt->second.begin(); !isCoincide && aCIt != anIt->second.end(); ++aCIt)
1053         if (*aCIt != theEntity && isUsed((*aCIt)->baseAttribute()))
1054           isCoincide = true;
1055     }
1056   }
1057
1058   std::shared_ptr<SolveSpaceSolver_EntityWrapper> anEntity = 
1059         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theEntity);
1060   bool isFullyRemoved = isCoincide ? true : removeEntity((Slvs_hEntity)anEntity->id());
1061   return (SketchSolver_Storage::remove(theEntity) || isCoincide) && isFullyRemoved;
1062 }
1063
1064 bool SolveSpaceSolver_Storage::remove(ParameterWrapperPtr theParameter)
1065 {
1066   return removeParameter((Slvs_hParam)theParameter->id());
1067 }
1068
1069
1070 void SolveSpaceSolver_Storage::refresh(bool theFixedOnly) const
1071 {
1072   //blockEvents(true);
1073
1074   std::map<AttributePtr, EntityWrapperPtr>::const_iterator anIt = myAttributeMap.begin();
1075   std::list<ParameterWrapperPtr> aParams;
1076   std::list<ParameterWrapperPtr>::const_iterator aParIt;
1077   for (; anIt != myAttributeMap.end(); ++anIt) {
1078     if (!anIt->second)
1079       continue;
1080     // the external feature always should keep the up to date values, so, 
1081     // refresh from the solver is never needed
1082     if (anIt->first.get()) {
1083       std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
1084         std::dynamic_pointer_cast<SketchPlugin_Feature>(anIt->first->owner());
1085       if (aSketchFeature.get() && aSketchFeature->isExternal())
1086         continue;
1087       // not need to refresh here sketch's origin and normal vector
1088       CompositeFeaturePtr aSketch =
1089           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(anIt->first->owner());
1090       if (aSketch)
1091         continue;
1092     }
1093
1094     // update parameter wrappers and obtain values of attributes
1095     aParams = anIt->second->parameters();
1096     double aCoords[3];
1097     bool isUpd[3] = {false};
1098     int i = 0;
1099     for (aParIt = aParams.begin(); i < 3 && aParIt != aParams.end(); ++aParIt, ++i) {
1100       std::shared_ptr<SolveSpaceSolver_ParameterWrapper> aWrapper = 
1101           std::dynamic_pointer_cast<SolveSpaceSolver_ParameterWrapper>(*aParIt);
1102       if (!theFixedOnly || aWrapper->group() == GID_OUTOFGROUP || aWrapper->isParametric()) {
1103         aWrapper->changeParameter().val = getParameter((Slvs_hParam)aWrapper->id()).val;
1104         aCoords[i] = aWrapper->value();
1105         isUpd[i] = true;
1106       }
1107     }
1108     if (!isUpd[0] && !isUpd[1] && !isUpd[2])
1109       continue; // nothing is updated
1110
1111     std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
1112         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anIt->first);
1113     if (aPoint2D) {
1114       if ((isUpd[0] && fabs(aPoint2D->x() - aCoords[0]) > tolerance) ||
1115           (isUpd[1] && fabs(aPoint2D->y() - aCoords[1]) > tolerance)) {
1116         if (!isUpd[0]) aCoords[0] = aPoint2D->x();
1117         if (!isUpd[1]) aCoords[1] = aPoint2D->y();
1118         aPoint2D->setValue(aCoords[0], aCoords[1]);
1119         // Find points coincident with this one (probably not in GID_OUTOFGROUP)
1120         std::map<AttributePtr, EntityWrapperPtr>::const_iterator aLocIt;
1121         if (theFixedOnly) 
1122           aLocIt = myAttributeMap.begin();
1123         else {
1124           aLocIt = anIt;
1125           ++aLocIt;
1126         }
1127         for (; aLocIt != myAttributeMap.end(); ++aLocIt) {
1128           if (!aLocIt->second)
1129             continue;
1130           std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
1131             std::dynamic_pointer_cast<SketchPlugin_Feature>(aLocIt->first->owner());
1132           if (aSketchFeature && aSketchFeature->isExternal())
1133             continue;
1134           if (anIt->second->id() == aLocIt->second->id()) {
1135             aPoint2D = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aLocIt->first);
1136             aPoint2D->setValue(aCoords[0], aCoords[1]);
1137           }
1138         }
1139       }
1140       continue;
1141     }
1142     AttributeDoublePtr aScalar = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(anIt->first);
1143     if (aScalar) {
1144       if (isUpd[0] && fabs(aScalar->value() - aCoords[0]) > tolerance)
1145         aScalar->setValue(aCoords[0]);
1146       continue;
1147     }
1148     std::shared_ptr<GeomDataAPI_Point> aPoint =
1149         std::dynamic_pointer_cast<GeomDataAPI_Point>(anIt->first);
1150     if (aPoint) {
1151       if ((isUpd[0] && fabs(aPoint->x() - aCoords[0]) > tolerance) ||
1152           (isUpd[1] && fabs(aPoint->y() - aCoords[1]) > tolerance) ||
1153           (isUpd[2] && fabs(aPoint->z() - aCoords[2]) > tolerance))
1154         if (!isUpd[0]) aCoords[0] = aPoint->x();
1155         if (!isUpd[1]) aCoords[1] = aPoint->y();
1156         if (!isUpd[2]) aCoords[2] = aPoint->z();
1157         aPoint->setValue(aCoords[0], aCoords[1], aCoords[2]);
1158       continue;
1159     }
1160   }
1161
1162   //blockEvents(false);
1163 }
1164
1165 void SolveSpaceSolver_Storage::verifyFixed()
1166 {
1167   std::map<AttributePtr, EntityWrapperPtr>::iterator anAttrIt = myAttributeMap.begin();
1168   for (; anAttrIt != myAttributeMap.end(); ++anAttrIt) {
1169     if (!anAttrIt->second)
1170       continue;
1171     if (anAttrIt->second->group() == GID_OUTOFGROUP) {
1172       Slvs_Entity anEnt = getEntity((Slvs_hEntity)anAttrIt->second->id());
1173       if (anEnt.group != (Slvs_hEntity)GID_OUTOFGROUP)
1174         anEnt.group = (Slvs_hEntity)GID_OUTOFGROUP;
1175       updateEntity(anEnt);
1176     }
1177
1178     const std::list<ParameterWrapperPtr>& aParameters = anAttrIt->second->parameters();
1179     std::list<ParameterWrapperPtr>::const_iterator aParIt = aParameters.begin();
1180     for (; aParIt != aParameters.end(); ++aParIt)
1181       if (anAttrIt->second->group() == GID_OUTOFGROUP || (*aParIt)->group() == GID_OUTOFGROUP) {
1182         Slvs_Param aParam = getParameter((Slvs_hParam)(*aParIt)->id());
1183         if (aParam.group != (Slvs_hParam)GID_OUTOFGROUP) {
1184           aParam.group = (Slvs_hParam)GID_OUTOFGROUP;
1185           updateParameter(aParam);
1186         }
1187       }
1188   }
1189 }
1190
1191
1192 void SolveSpaceSolver_Storage::adjustArc(const Slvs_Entity& theArc)
1193 {
1194   double anArcPoints[3][2];
1195   double aDist[3] = {0.0};
1196   bool isFixed[3] = {false};
1197   for (int i = 0; i < 3; ++i) {
1198     Slvs_Entity aPoint = getEntity(theArc.point[i]);
1199     isFixed[i] = (aPoint.group != (Slvs_hGroup)myGroupID);
1200     anArcPoints[i][0] = getParameter(aPoint.param[0]).val;
1201     anArcPoints[i][1] = getParameter(aPoint.param[1]).val;
1202     if (i > 0) {
1203       anArcPoints[i][0] -= anArcPoints[0][0];
1204       anArcPoints[i][1] -= anArcPoints[0][1];
1205       aDist[i] = sqrt(anArcPoints[i][0] * anArcPoints[i][0] + 
1206                       anArcPoints[i][1] * anArcPoints[i][1]);
1207     }
1208   }
1209
1210   if (fabs(aDist[1] - aDist[2]) < tolerance)
1211     return;
1212
1213   int anInd = 2;
1214   while (anInd > 0 && isFixed[anInd])
1215     --anInd;
1216   if (anInd < 1)
1217     return; // adjust only start or end point of the arc
1218
1219   anArcPoints[anInd][0] /= aDist[anInd];
1220   anArcPoints[anInd][1] /= aDist[anInd];
1221
1222   Slvs_Entity aPoint = getEntity(theArc.point[anInd]);
1223   for (int i = 0; i < 2; ++i) {
1224     Slvs_Param aParam = getParameter(aPoint.param[i]);
1225     aParam.val = anArcPoints[0][i] + aDist[3-anInd] * anArcPoints[anInd][i];
1226     updateParameter(aParam);
1227   }
1228 }
1229
1230
1231
1232
1233
1234
1235
1236 // ========================================================
1237 // =========      Auxiliary functions       ===============
1238 // ========================================================
1239
1240 template<typename T>
1241 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1242 {
1243   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1244   int aVecSize = (int)theEntities.size();
1245   if (theEntities.empty())
1246     return 1;
1247   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1248     aResIndex--;
1249   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1250     aResIndex++;
1251   if (aResIndex == -1 || (aResIndex < aVecSize && theEntities[aResIndex].h != theEntityID))
1252     aResIndex = aVecSize;
1253   return aResIndex;
1254 }
1255
1256 bool IsNotEqual(const Slvs_Param& theParam1, const Slvs_Param& theParam2)
1257 {
1258   return fabs(theParam1.val - theParam2.val) > tolerance;
1259 }
1260
1261 bool IsNotEqual(const Slvs_Entity& theEntity1, const Slvs_Entity& theEntity2)
1262 {
1263   int i = 0;
1264   for (; theEntity1.param[i] != 0 && i < 4; i++)
1265     if (theEntity1.param[i] != theEntity2.param[i])
1266       return true;
1267   i = 0;
1268   for (; theEntity1.point[i] != 0 && i < 4; i++)
1269     if (theEntity1.point[i] != theEntity2.point[i])
1270       return true;
1271   return false;
1272 }
1273
1274 bool IsNotEqual(const Slvs_Constraint& theConstraint1, const Slvs_Constraint& theConstraint2)
1275 {
1276   return theConstraint1.ptA != theConstraint2.ptA ||
1277          theConstraint1.ptB != theConstraint2.ptB ||
1278          theConstraint1.entityA != theConstraint2.entityA ||
1279          theConstraint1.entityB != theConstraint2.entityB ||
1280          theConstraint1.entityC != theConstraint2.entityC ||
1281          theConstraint1.entityD != theConstraint2.entityD ||
1282          fabs(theConstraint1.valA - theConstraint2.valA) > tolerance;
1283 }