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