Salome HOME
Correct processing arcs in SketchSolver with SolveSpace (issue #1144)
[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 <SketchPlugin_Arc.h>
23
24 /** \brief Search the entity/parameter with specified ID in the list of elements
25  *  \param[in] theEntityID unique ID of the element
26  *  \param[in] theEntities list of elements
27  *  \return position of the found element or -1 if the element is not found
28  */
29 template<typename T>
30 static int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities);
31
32 /// \brief Compare two parameters to be different
33 static bool IsNotEqual(const Slvs_Param& theParam1, const Slvs_Param& theParam2);
34 /// \brief Compare two entities to be different
35 static bool IsNotEqual(const Slvs_Entity& theEntity1, const Slvs_Entity& theEntity2);
36 /// \brief Compare two constraints to be different
37 static bool IsNotEqual(const Slvs_Constraint& theConstraint1, const Slvs_Constraint& theConstraint2);
38
39
40 SolveSpaceSolver_Storage::SolveSpaceSolver_Storage(const GroupID& theGroup)
41   : SketchSolver_Storage(theGroup),
42     myWorkplaneID(SLVS_E_UNKNOWN),
43     myParamMaxID(SLVS_E_UNKNOWN),
44     myEntityMaxID(SLVS_E_UNKNOWN),
45     myConstrMaxID(SLVS_C_UNKNOWN),
46     myFixed(SLVS_E_UNKNOWN),
47     myDuplicatedConstraint(false)
48 {
49 }
50
51 bool SolveSpaceSolver_Storage::update(ConstraintWrapperPtr& theConstraint)
52 {
53   bool isUpdated = false;
54   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
55       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
56   Slvs_Constraint aSlvsConstr = getConstraint((Slvs_hConstraint)aConstraint->id());
57   if (aSlvsConstr.h == SLVS_C_UNKNOWN)
58     aSlvsConstr = aConstraint->constraint();
59
60   // update value of constraint if exist
61   if (fabs(aSlvsConstr.valA - theConstraint->value()) > tolerance) {
62     aSlvsConstr.valA = theConstraint->value();
63     isUpdated = true;
64   }
65
66   // update constrained entities
67   Slvs_hEntity* aPnts[2] = {&aSlvsConstr.ptA, &aSlvsConstr.ptB};
68   Slvs_hEntity* anEnts[4] = {&aSlvsConstr.entityA, &aSlvsConstr.entityB,
69                              &aSlvsConstr.entityC, &aSlvsConstr.entityD};
70   int aPtInd = 0;
71   int aEntInd = 0;
72
73   std::list<EntityWrapperPtr> anEntities = theConstraint->entities();
74   std::list<EntityWrapperPtr>::iterator anIt = anEntities.begin();
75   for (; anIt != anEntities.end(); ++anIt) {
76     isUpdated = update(*anIt) || isUpdated;
77     // do not update constrained entities for Multi constraints
78     if (aSlvsConstr.type == SLVS_C_MULTI_ROTATION || aSlvsConstr.type != SLVS_C_MULTI_TRANSLATION)
79       continue;
80
81     Slvs_hEntity anID = (Slvs_hEntity)(*anIt)->id();
82     if ((*anIt)->type() == ENTITY_POINT) {
83       if (*(aPnts[aPtInd]) != anID) {
84         *(aPnts[aPtInd]) = anID;
85         isUpdated = true;
86       }
87       ++aPtInd;
88     } else {
89       if (*(anEnts[aEntInd]) != anID) {
90         *(anEnts[aEntInd]) = anID;
91         isUpdated = true;
92       }
93       ++aEntInd;
94     }
95   }
96
97   // update constraint itself (do not update constraints Multi)
98   if (aSlvsConstr.type != SLVS_C_MULTI_ROTATION && aSlvsConstr.type != SLVS_C_MULTI_TRANSLATION) {
99     if (aSlvsConstr.wrkpl == SLVS_E_UNKNOWN && myWorkplaneID != SLVS_E_UNKNOWN)
100       aSlvsConstr.wrkpl = myWorkplaneID;
101     if (aSlvsConstr.group == SLVS_G_UNKNOWN)
102       aSlvsConstr.group = (Slvs_hGroup)myGroupID;
103     Slvs_hConstraint aConstrID = updateConstraint(aSlvsConstr);
104     if (aSlvsConstr.h == SLVS_C_UNKNOWN) {
105       aConstraint->changeConstraint() = getConstraint(aConstrID);
106       isUpdated = true;
107     }
108   }
109   return isUpdated;
110 }
111
112 bool SolveSpaceSolver_Storage::update(EntityWrapperPtr& theEntity)
113 {
114   bool isUpdated = false;
115   std::shared_ptr<SolveSpaceSolver_EntityWrapper> anEntity = 
116       std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theEntity);
117   Slvs_Entity aSlvsEnt = getEntity((Slvs_hEntity)anEntity->id());
118   if (aSlvsEnt.h == SLVS_E_UNKNOWN)
119     aSlvsEnt = anEntity->entity();
120
121   std::list<ParameterWrapperPtr> aParams = theEntity->parameters();
122   std::list<ParameterWrapperPtr>::iterator aPIt;
123   // if the entity is an attribute, need to update its coordinates
124   if (anEntity->baseAttribute()) {
125     BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
126     EntityWrapperPtr anUpdAttr = aBuilder->createAttribute(anEntity->baseAttribute(), GID_UNKNOWN);
127     if (anUpdAttr) {
128       std::list<ParameterWrapperPtr> anUpdParams = anUpdAttr->parameters();
129       std::list<ParameterWrapperPtr>::iterator anUpdIt = anUpdParams.begin();
130       for (aPIt = aParams.begin(); aPIt != aParams.end() && anUpdIt != anUpdParams.end();
131           ++aPIt, ++anUpdIt) {
132         (*aPIt)->update(*anUpdIt);
133       }
134     }
135   }
136
137   // update parameters
138   int anInd = 0;
139   for (aPIt = aParams.begin(); aPIt != aParams.end(); ++aPIt, ++anInd) {
140     assert(anInd < 4);
141     isUpdated = update(*aPIt) || isUpdated;
142     if (aSlvsEnt.param[anInd] != (Slvs_hEntity)(*aPIt)->id()) {
143       isUpdated = true;
144       aSlvsEnt.param[anInd] = (Slvs_hEntity)(*aPIt)->id();
145     }
146   }
147
148   // update sub-entities
149   std::list<EntityWrapperPtr> aSubEntities = theEntity->subEntities();
150   std::list<EntityWrapperPtr>::iterator aSIt = aSubEntities.begin();
151   for (anInd = 0; aSIt != aSubEntities.end(); ++aSIt, ++anInd) {
152     assert(anInd < 4);
153     isUpdated = update(*aSIt) || isUpdated;
154
155     Slvs_hEntity anID = Slvs_hEntity((*aSIt)->id());
156     if ((*aSIt)->type() == ENTITY_NORMAL)
157       aSlvsEnt.normal = anID;
158     else if ((*aSIt)->type() == ENTITY_SCALAR)
159       aSlvsEnt.distance = anID;
160     else if (aSlvsEnt.point[anInd] != anID) {
161       aSlvsEnt.point[anInd] = anID;
162       isUpdated = true;
163     }
164   }
165   if (theEntity->type() == ENTITY_POINT && aSubEntities.size() == 1) {
166     // theEntity is based on SketchPlugin_Point => need to substitute its attribute instead
167     bool isNew = (aSlvsEnt.h == SLVS_E_UNKNOWN);
168     aSlvsEnt = getEntity(aSlvsEnt.point[0]);
169     if (isNew) {
170       anEntity->changeEntity() = aSlvsEnt;
171       isUpdated = true;
172     }
173   }
174
175   // update entity itself
176   if (aSlvsEnt.wrkpl == SLVS_E_UNKNOWN && myWorkplaneID != SLVS_E_UNKNOWN)
177     aSlvsEnt.wrkpl = myWorkplaneID;
178   if (aSlvsEnt.group == SLVS_G_UNKNOWN)
179     aSlvsEnt.group = (Slvs_hGroup)myGroupID;
180   Slvs_hEntity anEntID = updateEntity(aSlvsEnt);
181   if (aSlvsEnt.h == SLVS_E_UNKNOWN) {
182     anEntity->changeEntity() = getEntity(anEntID);
183     isUpdated = true;
184
185     if (anEntity->type() == ENTITY_SKETCH)
186       storeWorkplane(anEntity);
187
188     // For the correct work with arcs we will add them if their parameter is added
189     if (theEntity->baseAttribute()) {
190       FeaturePtr aFeature = ModelAPI_Feature::feature(theEntity->baseAttribute()->owner());
191       if (aFeature->getKind() == SketchPlugin_Arc::ID() &&
192           myFeatureMap.find(aFeature) == myFeatureMap.end()) {
193         // Additional checking that all attributes are initialized
194         if (aFeature->attribute(SketchPlugin_Arc::CENTER_ID())->isInitialized() && 
195             aFeature->attribute(SketchPlugin_Arc::START_ID())->isInitialized() && 
196             aFeature->attribute(SketchPlugin_Arc::END_ID())->isInitialized()) {
197           myFeatureMap[aFeature] = EntityWrapperPtr();
198           return SketchSolver_Storage::update(aFeature);
199         }
200       }
201     }
202   }
203
204   return isUpdated;
205 }
206
207 bool SolveSpaceSolver_Storage::update(ParameterWrapperPtr& theParameter)
208 {
209   std::shared_ptr<SolveSpaceSolver_ParameterWrapper> aParameter = 
210       std::dynamic_pointer_cast<SolveSpaceSolver_ParameterWrapper>(theParameter);
211   const Slvs_Param& aParam = getParameter((Slvs_hParam)aParameter->id());
212   if (aParam.h != SLVS_E_UNKNOWN && fabs(aParam.val - aParameter->value()) < tolerance)
213     return false;
214   Slvs_Param aParamToUpd = aParameter->parameter();
215   if (aParamToUpd.group == SLVS_G_UNKNOWN)
216     aParamToUpd.group = aParameter->isParametric() ? (Slvs_hGroup)GID_OUTOFGROUP : (Slvs_hGroup)myGroupID;
217   Slvs_hParam anID = updateParameter(aParamToUpd);
218   if (aParam.h == SLVS_E_UNKNOWN) // new parameter
219     aParameter->changeParameter() = getParameter(anID);
220   return true;
221 }
222
223 void SolveSpaceSolver_Storage::storeWorkplane(EntityWrapperPtr theSketch)
224 {
225   myWorkplaneID = (Slvs_hEntity)theSketch->id();
226
227   // Update sub-entities of the sketch
228   std::list<EntityWrapperPtr> aSubEntities = theSketch->subEntities();
229   std::list<EntityWrapperPtr>::iterator aSIt = aSubEntities.begin();
230   for (; aSIt != aSubEntities.end(); ++aSIt) {
231     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aSub =
232         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*aSIt);
233     aSub->changeEntity().wrkpl = myWorkplaneID;
234   }
235
236   // Update all stored entities
237   std::vector<Slvs_Entity>::iterator anIt = myEntities.begin();
238   for (; anIt != myEntities.end(); ++anIt)
239     anIt->wrkpl = myWorkplaneID;
240 }
241
242 void SolveSpaceSolver_Storage::changeGroup(EntityWrapperPtr theEntity, const GroupID& theGroup)
243 {
244   std::list<ParameterWrapperPtr> aParams = theEntity->parameters();
245   std::list<ParameterWrapperPtr>::iterator aPIt = aParams.begin();
246   for (; aPIt != aParams.end(); ++aPIt)
247     changeGroup(*aPIt, theGroup);
248
249   std::list<EntityWrapperPtr> aSubs = theEntity->subEntities();
250   std::list<EntityWrapperPtr>::iterator aSIt = aSubs.begin();
251   for (; aSIt != aSubs.end(); ++aSIt)
252     changeGroup(*aSIt, theGroup);
253
254   if (theEntity->group() != theGroup) {
255     theEntity->setGroup(theGroup);
256     int aPos = Search((Slvs_hEntity)theEntity->id(), myEntities);
257     if (aPos >= 0 && aPos < (int)myEntities.size()) {
258       myEntities[aPos].group = (Slvs_hGroup)theGroup;
259       setNeedToResolve(true);
260     }
261   }
262 }
263
264 void SolveSpaceSolver_Storage::changeGroup(ParameterWrapperPtr theParam, const GroupID& theGroup)
265 {
266   GroupID aGroup = theGroup;
267   if (theParam->isParametric())
268     aGroup = GID_OUTOFGROUP;
269   if (theParam->group() == aGroup)
270     return;
271
272   theParam->setGroup(aGroup);
273   int aPos = Search((Slvs_hParam)theParam->id(), myParameters);
274   if (aPos >= 0 && aPos < (int)myParameters.size()) {
275     myParameters[aPos].group = (Slvs_hGroup)aGroup;
276     setNeedToResolve(true);
277   }
278 }
279
280 void SolveSpaceSolver_Storage::addCoincidentPoints(
281     EntityWrapperPtr theMaster, EntityWrapperPtr theSlave)
282 {
283   if (theMaster->type() != ENTITY_POINT || theSlave->type() != ENTITY_POINT)
284     return;
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
382       // (these constraints are stored to keep the structure of constraints).
383       if ((*aCIt)->type() == CONSTRAINT_PT_PT_COINCIDENT)
384         continue;
385
386       bool isUpdated = false;
387       std::list<EntityWrapperPtr> aSubs = (*aCIt)->entities();
388       std::list<EntityWrapperPtr>::iterator aSubIt = aSubs.begin();
389       for (; aSubIt != aSubs.end(); ++aSubIt)
390         if ((*aSubIt)->id() == theSource->id()) {
391           (*aSubIt)->update(theDest);
392           isUpdated = true;
393         }
394
395       if (!isUpdated)
396         continue;
397
398       std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aWrapper =
399           std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(*aCIt);
400       // change constraint entities
401       Slvs_Constraint aConstr = aWrapper->constraint();
402       if (aConstr.ptA == (Slvs_hEntity)theSource->id())
403         aConstr.ptA = (Slvs_hEntity)theDest->id();
404       if (aConstr.ptB == (Slvs_hEntity)theSource->id())
405         aConstr.ptB = (Slvs_hEntity)theDest->id();
406
407       // check the constraint is duplicated
408       std::vector<Slvs_Constraint>::const_iterator aSlvsCIt = myConstraints.begin();
409       for (; aSlvsCIt != myConstraints.end(); ++aSlvsCIt)
410         if (aConstr.h != aSlvsCIt->h &&
411             aConstr.type == aSlvsCIt->type &&
412             aConstr.ptA == aSlvsCIt->ptA && aConstr.ptB == aSlvsCIt->ptB &&
413             aConstr.entityA == aSlvsCIt->entityA && aConstr.entityB == aSlvsCIt->entityB &&
414             aConstr.entityC == aSlvsCIt->entityC && aConstr.entityD == aSlvsCIt->entityD) {
415           removeConstraint(aConstr.h);
416           aConstr = *aSlvsCIt;
417           break;
418         }
419
420       if (aSlvsCIt != myConstraints.end()) {
421         // constraint is duplicated, search its wrapper to add the mapping
422         std::map<ConstraintPtr, std::list<ConstraintWrapperPtr> >::const_iterator
423             anIt2 = myConstraintMap.begin();
424         std::list<ConstraintWrapperPtr>::const_iterator aCIt2;
425         for (; anIt2 != myConstraintMap.end(); ++anIt2)
426           for (aCIt2 = anIt2->second.begin(); aCIt2 != anIt2->second.end(); ++aCIt2)
427             if ((Slvs_hConstraint)(*aCIt2)->id() == aConstr.h) {
428               addSameConstraints(*aCIt2, aWrapper);
429               break;
430             }
431       } else 
432         aConstr.h = updateConstraint(aConstr);
433       aWrapper->changeConstraint() = aConstr;
434
435       // update sub-entities
436       aWrapper->setEntities(aSubs);
437     }
438 }
439
440 void SolveSpaceSolver_Storage::addSameConstraints(ConstraintWrapperPtr theConstraint1,
441                                                   ConstraintWrapperPtr theConstraint2)
442 {
443   SameConstraintMap::iterator anIt = myEqualConstraints.begin();
444   for (; anIt != myEqualConstraints.end(); ++anIt) {
445     if (anIt->find(theConstraint1) != anIt->end()) {
446       anIt->insert(theConstraint2);
447       return;
448     }
449     else if (anIt->find(theConstraint2) != anIt->end()) {
450       anIt->insert(theConstraint1);
451       return;
452     }
453   }
454   // group not found => create new one
455   std::set<ConstraintWrapperPtr> aNewGroup;
456   aNewGroup.insert(theConstraint1);
457   aNewGroup.insert(theConstraint2);
458   myEqualConstraints.push_back(aNewGroup);
459 }
460
461
462 EntityWrapperPtr SolveSpaceSolver_Storage::calculateMiddlePoint(
463     EntityWrapperPtr theBase, double theCoeff)
464 {
465   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
466
467   std::shared_ptr<GeomAPI_XY> aMidPoint;
468   if (theBase->type() == ENTITY_LINE) {
469     std::shared_ptr<GeomAPI_Pnt2d> aPoints[2];
470     const std::list<EntityWrapperPtr>& aSubs = theBase->subEntities();
471     std::list<EntityWrapperPtr>::const_iterator anIt = aSubs.begin();
472     for (int i = 0; i < 2; ++i, ++anIt)
473       aPoints[i] = aBuilder->point(*anIt);
474     aMidPoint = aPoints[0]->xy()->multiplied(1.0 - theCoeff)->added(
475         aPoints[1]->xy()->multiplied(theCoeff));
476   }
477   else if (theBase->type() == ENTITY_ARC) {
478     double theX, theY;
479     double anArcPoint[3][2];
480     const std::list<EntityWrapperPtr>& aSubs = theBase->subEntities();
481     std::list<EntityWrapperPtr>::const_iterator anIt = aSubs.begin();
482     for (int i = 0; i < 3; ++i, ++anIt) {
483       std::shared_ptr<GeomAPI_Pnt2d> aPoint = aBuilder->point(*anIt);
484       anArcPoint[i][0] = aPoint->x();
485       anArcPoint[i][1] = aPoint->y();
486     }
487     // project last point of arc on the arc
488     double x = anArcPoint[1][0] - anArcPoint[0][0];
489     double y = anArcPoint[1][1] - anArcPoint[0][1];
490     double aRad = sqrt(x*x + y*y);
491     x = anArcPoint[2][0] - anArcPoint[0][0];
492     y = anArcPoint[2][1] - anArcPoint[0][1];
493     double aNorm = sqrt(x*x + y*y);
494     if (aNorm >= tolerance) {
495       anArcPoint[2][0] = x * aRad / aNorm;
496       anArcPoint[2][1] = y * aRad / aNorm;
497     }
498     anArcPoint[1][0] -= anArcPoint[0][0];
499     anArcPoint[1][1] -= anArcPoint[0][1];
500     if (theCoeff < tolerance) {
501       theX = anArcPoint[0][0] + anArcPoint[1][0];
502       theY = anArcPoint[0][1] + anArcPoint[1][1];
503     } else if (1 - theCoeff < tolerance) {
504       theX = anArcPoint[0][0] + anArcPoint[2][0];
505       theY = anArcPoint[0][1] + anArcPoint[2][1];
506     } else {
507       std::shared_ptr<GeomAPI_Dir2d> aStartDir(new GeomAPI_Dir2d(anArcPoint[1][0], anArcPoint[1][1]));
508       std::shared_ptr<GeomAPI_Dir2d> aEndDir(new GeomAPI_Dir2d(anArcPoint[2][0], anArcPoint[2][1]));
509       double anAngle = aStartDir->angle(aEndDir);
510       if (anAngle < 0)
511         anAngle += 2.0 * PI;
512       anAngle *= theCoeff;
513       double aCos = cos(anAngle);
514       double aSin = sin(anAngle);
515       theX = anArcPoint[0][0] + anArcPoint[1][0] * aCos - anArcPoint[1][1] * aSin;
516       theY = anArcPoint[0][1] + anArcPoint[1][0] * aSin + anArcPoint[1][1] * aCos;
517     }
518     aMidPoint = std::shared_ptr<GeomAPI_XY>(new GeomAPI_XY(theX, theY));
519   }
520
521   if (!aMidPoint)
522     return EntityWrapperPtr();
523
524   std::list<ParameterWrapperPtr> aParameters;
525   Slvs_Param aParam1 = Slvs_MakeParam(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID, aMidPoint->x());
526   aParam1.h = addParameter(aParam1);
527   aParameters.push_back(ParameterWrapperPtr(new SolveSpaceSolver_ParameterWrapper(aParam1)));
528   Slvs_Param aParam2 = Slvs_MakeParam(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID, aMidPoint->y());
529   aParam2.h = addParameter(aParam2);
530   aParameters.push_back(ParameterWrapperPtr(new SolveSpaceSolver_ParameterWrapper(aParam2)));
531   // Create entity (parameters are not filled)
532   Slvs_Entity anEntity = Slvs_MakePoint2d(SLVS_E_UNKNOWN, (Slvs_hGroup)myGroupID,
533       (Slvs_hEntity)myWorkplaneID, aParam1.h, aParam2.h);
534   anEntity.h = addEntity(anEntity);
535
536   EntityWrapperPtr aResult(new SolveSpaceSolver_EntityWrapper(AttributePtr(), anEntity));
537   aResult->setParameters(aParameters);
538   return aResult;
539 }
540
541
542
543
544
545
546 Slvs_hParam SolveSpaceSolver_Storage::addParameter(const Slvs_Param& theParam)
547 {
548   if (theParam.h > 0 && theParam.h <= myParamMaxID) {
549     // parameter is already used, rewrite it
550     return updateParameter(theParam);
551   }
552
553   Slvs_Param aParam = theParam;
554   if (aParam.h > myParamMaxID)
555     myParamMaxID = aParam.h;
556   else
557     aParam.h = ++myParamMaxID;
558   myParameters.push_back(aParam);
559   myNeedToResolve = true;
560   return aParam.h;
561 }
562
563 Slvs_hParam SolveSpaceSolver_Storage::updateParameter(const Slvs_Param& theParam)
564 {
565   if (theParam.h > 0 && theParam.h <= myParamMaxID) {
566     // parameter already used, rewrite it
567     int aPos = Search(theParam.h, myParameters);
568     if (aPos >= 0 && aPos < (int)myParameters.size()) {
569       if (IsNotEqual(myParameters[aPos], theParam)) {
570         myUpdatedParameters.insert(theParam.h);
571         setNeedToResolve(true);
572       }
573       myParameters[aPos] = theParam;
574       return theParam.h;
575     }
576   }
577
578   // Parameter is not found, add new one
579   Slvs_Param aParam = theParam;
580   aParam.h = 0;
581   return addParameter(aParam);
582 }
583
584 bool SolveSpaceSolver_Storage::removeParameter(const Slvs_hParam& theParamID)
585 {
586   int aPos = Search(theParamID, myParameters);
587   if (aPos >= 0 && aPos < (int)myParameters.size()) {
588     // Firstly, search the parameter is not used elsewhere
589     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
590     for (; anEntIter != myEntities.end(); anEntIter++) {
591       for (int i = 0; i < 4; i++)
592         if (anEntIter->param[i] == theParamID)
593           return false;
594     }
595     // Remove parameter
596     myParameters.erase(myParameters.begin() + aPos);
597     myParamMaxID = myParameters.empty() ? SLVS_E_UNKNOWN : myParameters.back().h;
598     myNeedToResolve = true;
599   }
600   return true;
601 }
602
603 const Slvs_Param& SolveSpaceSolver_Storage::getParameter(const Slvs_hParam& theParamID) const
604 {
605   int aPos = Search(theParamID, myParameters);
606   if (aPos >= 0 && aPos < (int)myParameters.size())
607     return myParameters[aPos];
608
609   // Parameter is not found, return empty object
610   static Slvs_Param aDummy;
611   aDummy.h = 0;
612   return aDummy;
613 }
614
615
616 Slvs_hEntity SolveSpaceSolver_Storage::addEntity(const Slvs_Entity& theEntity)
617 {
618   if (theEntity.h > 0 && theEntity.h <= myEntityMaxID) {
619     // Entity is already used, rewrite it
620     return updateEntity(theEntity);
621   }
622
623   Slvs_Entity aEntity = theEntity;
624   if (aEntity.h > myEntityMaxID)
625     myEntityMaxID = aEntity.h;
626   else
627     aEntity.h = ++myEntityMaxID;
628   myEntities.push_back(aEntity);
629   myNeedToResolve = true;
630   return aEntity.h;
631 }
632
633 Slvs_hEntity SolveSpaceSolver_Storage::updateEntity(const Slvs_Entity& theEntity)
634 {
635   if (theEntity.h > 0 && theEntity.h <= myEntityMaxID) {
636     // Entity already used, rewrite it
637     int aPos = Search(theEntity.h, myEntities);
638     if (aPos >= 0 && aPos < (int)myEntities.size()) {
639       myNeedToResolve = myNeedToResolve || IsNotEqual(myEntities[aPos], theEntity);
640       myEntities[aPos] = theEntity;
641       return theEntity.h;
642     }
643   }
644
645   // Entity is not found, add new one
646   Slvs_Entity aEntity = theEntity;
647   aEntity.h = 0;
648   return addEntity(aEntity);
649 }
650
651 bool SolveSpaceSolver_Storage::removeEntity(const Slvs_hEntity& theEntityID)
652 {
653   bool aResult = true;
654   int aPos = Search(theEntityID, myEntities);
655   if (aPos >= 0 && aPos < (int)myEntities.size()) {
656     // Firstly, check the entity and its attributes is not used elsewhere
657     std::set<Slvs_hEntity> anEntAndSubs;
658     anEntAndSubs.insert(theEntityID);
659     for (int i = 0; i < 4; i++)
660       if (myEntities[aPos].point[i] != SLVS_E_UNKNOWN)
661         anEntAndSubs.insert(myEntities[aPos].point[i]);
662
663     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
664     for (; anEntIter != myEntities.end(); anEntIter++) {
665       if (anEntAndSubs.find(anEntIter->h) != anEntAndSubs.end())
666         continue;
667       for (int i = 0; i < 4; i++)
668         if (anEntAndSubs.find(anEntIter->point[i]) != anEntAndSubs.end())
669           return false;
670       if (anEntAndSubs.find(anEntIter->distance) != anEntAndSubs.end())
671         return false;
672     }
673     std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
674     for (; aConstrIter != myConstraints.end(); aConstrIter++) {
675       Slvs_hEntity anEntIDs[6] = {aConstrIter->ptA, aConstrIter->ptB,
676           aConstrIter->entityA, aConstrIter->entityB,
677           aConstrIter->entityC, aConstrIter->entityD};
678       for (int i = 0; i < 6; i++)
679         if (anEntAndSubs.find(anEntIDs[i]) != anEntAndSubs.end())
680           return false;
681     }
682     // The entity is not used, remove it and its parameters
683     Slvs_Entity anEntity = myEntities[aPos];
684     myEntities.erase(myEntities.begin() + aPos);
685     myEntityMaxID = myEntities.empty() ? SLVS_E_UNKNOWN : myEntities.back().h;
686     if (anEntity.distance != SLVS_E_UNKNOWN)
687       aResult = aResult && removeParameter(anEntity.distance);
688     for (int i = 0; i < 4; i++)
689       if (anEntity.param[i] != SLVS_E_UNKNOWN)
690         aResult = removeParameter(anEntity.param[i]) && aResult;
691     for (int i = 0; i < 4; i++)
692       if (anEntity.point[i] != SLVS_E_UNKNOWN)
693         aResult = removeEntity(anEntity.point[i]) && aResult;
694     myNeedToResolve = true;
695   }
696   return aResult;
697 }
698
699 void SolveSpaceSolver_Storage::removeUnusedEntities()
700 {
701   std::set<Slvs_hEntity> anUnusedEntities;
702   std::vector<Slvs_Entity>::const_iterator aEIt = myEntities.begin();
703   for (; aEIt != myEntities.end(); ++aEIt) {
704     if (aEIt->h == aEIt->wrkpl) {
705       // don't remove workplane
706       anUnusedEntities.erase(aEIt->point[0]);
707       anUnusedEntities.erase(aEIt->normal);
708       continue;
709     }
710     anUnusedEntities.insert(aEIt->h);
711   }
712
713   std::vector<Slvs_Constraint>::const_iterator aCIt = myConstraints.begin();
714   for (; aCIt != myConstraints.end(); ++aCIt) {
715     Slvs_hEntity aSubs[6] = {
716         aCIt->entityA, aCIt->entityB,
717         aCIt->entityC, aCIt->entityD,
718         aCIt->ptA,     aCIt->ptB};
719     for (int i = 0; i < 6; i++) {
720       if (aSubs[i] != SLVS_E_UNKNOWN) {
721         anUnusedEntities.erase(aSubs[i]);
722         int aPos = Search(aSubs[i], myEntities);
723         if (aPos >= 0 && aPos < (int)myEntities.size()) {
724           for (int j = 0; j < 4; j++)
725             if (myEntities[aPos].point[j] != SLVS_E_UNKNOWN)
726               anUnusedEntities.erase(myEntities[aPos].point[j]);
727           if (myEntities[aPos].distance != SLVS_E_UNKNOWN)
728             anUnusedEntities.erase(myEntities[aPos].distance);
729         }
730       }
731     }
732   }
733
734   std::set<Slvs_hEntity>::const_iterator anEntIt = anUnusedEntities.begin();
735   while (anEntIt != anUnusedEntities.end()) {
736     int aPos = Search(*anEntIt, myEntities);
737     if (aPos < 0 && aPos >= (int)myEntities.size())
738       continue;
739     Slvs_Entity anEntity = myEntities[aPos];
740     // Remove entity if and only if all its parameters unused
741     bool isUsed = false;
742     if (anEntity.distance != SLVS_E_UNKNOWN && 
743       anUnusedEntities.find(anEntity.distance) == anUnusedEntities.end())
744       isUsed = true;
745     for (int i = 0; i < 4 && !isUsed; i++)
746       if (anEntity.point[i] != SLVS_E_UNKNOWN &&
747           anUnusedEntities.find(anEntity.point[i]) == anUnusedEntities.end())
748         isUsed = true;
749     if (isUsed) {
750       anUnusedEntities.erase(anEntity.distance);
751       for (int i = 0; i < 4; i++)
752         if (anEntity.point[i] != SLVS_E_UNKNOWN)
753           anUnusedEntities.erase(anEntity.point[i]);
754       std::set<Slvs_hEntity>::iterator aRemoveIt = anEntIt++;
755       anUnusedEntities.erase(aRemoveIt);
756       continue;
757     }
758     ++anEntIt;
759   }
760
761   for (anEntIt = anUnusedEntities.begin(); anEntIt != anUnusedEntities.end(); ++anEntIt) {
762     int aPos = Search(*anEntIt, myEntities);
763     if (aPos >= 0 && aPos < (int)myEntities.size()) {
764       // Remove entity and its parameters
765       Slvs_Entity anEntity = myEntities[aPos];
766       myEntities.erase(myEntities.begin() + aPos);
767       myEntityMaxID = myEntities.empty() ? SLVS_E_UNKNOWN : myEntities.back().h;
768       if (anEntity.distance != SLVS_E_UNKNOWN)
769         removeParameter(anEntity.distance);
770       for (int i = 0; i < 4; i++)
771         if (anEntity.param[i] != SLVS_E_UNKNOWN)
772           removeParameter(anEntity.param[i]);
773       for (int i = 0; i < 4; i++)
774         if (anEntity.point[i] != SLVS_E_UNKNOWN)
775           removeEntity(anEntity.point[i]);
776     }
777   }
778
779   if (!anUnusedEntities.empty())
780     myNeedToResolve = true;
781 }
782
783 bool SolveSpaceSolver_Storage::isUsedByConstraints(const Slvs_hEntity& theEntityID) const
784 {
785   std::vector<Slvs_Constraint>::const_iterator aCIt = myConstraints.begin();
786   for (; aCIt != myConstraints.end(); ++aCIt) {
787     Slvs_hEntity aSubs[6] = {
788         aCIt->entityA, aCIt->entityB,
789         aCIt->entityC, aCIt->entityD,
790         aCIt->ptA,     aCIt->ptB};
791     for (int i = 0; i < 6; i++)
792       if (aSubs[i] != SLVS_E_UNKNOWN && aSubs[i] == theEntityID)
793         return true;
794   }
795   return false;
796 }
797
798 const Slvs_Entity& SolveSpaceSolver_Storage::getEntity(const Slvs_hEntity& theEntityID) const
799 {
800   int aPos = Search(theEntityID, myEntities);
801   if (aPos >= 0 && aPos < (int)myEntities.size())
802     return myEntities[aPos];
803
804   // Entity is not found, return empty object
805   static Slvs_Entity aDummy;
806   aDummy.h = SLVS_E_UNKNOWN;
807   return aDummy;
808 }
809
810 Slvs_hEntity SolveSpaceSolver_Storage::copyEntity(const Slvs_hEntity& theCopied)
811 {
812   int aPos = Search(theCopied, myEntities);
813   if (aPos < 0 || aPos >= (int)myEntities.size())
814     return SLVS_E_UNKNOWN;
815
816   Slvs_Entity aCopy = myEntities[aPos];
817   aCopy.h = SLVS_E_UNKNOWN;
818   int i = 0;
819   while (aCopy.point[i] != SLVS_E_UNKNOWN) {
820     aCopy.point[i] = copyEntity(aCopy.point[i]);
821     i++;
822   }
823   if (aCopy.param[0] != SLVS_E_UNKNOWN) {
824     aPos = Search(aCopy.param[0], myParameters);
825     i = 0;
826     while (aCopy.param[i] != SLVS_E_UNKNOWN) {
827       Slvs_Param aNewParam = myParameters[aPos];
828       aNewParam.h = SLVS_E_UNKNOWN;
829       aCopy.param[i] = addParameter(aNewParam);
830       i++;
831       aPos++;
832     }
833   }
834   return addEntity(aCopy);
835 }
836
837 void SolveSpaceSolver_Storage::copyEntity(const Slvs_hEntity& theFrom, const Slvs_hEntity& theTo)
838 {
839   int aPosFrom = Search(theFrom, myEntities);
840   int aPosTo = Search(theTo, myEntities);
841   if (aPosFrom < 0 || aPosFrom >= (int)myEntities.size() || 
842       aPosTo < 0 || aPosTo >= (int)myEntities.size())
843     return;
844
845   Slvs_Entity aEntFrom = myEntities[aPosFrom];
846   Slvs_Entity aEntTo = myEntities[aPosTo];
847   int i = 0;
848   while (aEntFrom.point[i] != SLVS_E_UNKNOWN) {
849     copyEntity(aEntFrom.point[i], aEntTo.point[i]);
850     i++;
851   }
852   if (aEntFrom.param[0] != SLVS_E_UNKNOWN) {
853     aPosFrom = Search(aEntFrom.param[0], myParameters);
854     aPosTo = Search(aEntTo.param[0], myParameters);
855     i = 0;
856     while (aEntFrom.param[i] != SLVS_E_UNKNOWN) {
857       myParameters[aPosTo++].val = myParameters[aPosFrom++].val;
858       i++;
859     }
860   }
861 }
862
863
864 bool SolveSpaceSolver_Storage::isPointFixed(
865     const Slvs_hEntity& thePointID, Slvs_hConstraint& theFixed, bool theAccurate) const
866 {
867   // Search the set of coincident points
868   std::set<Slvs_hEntity> aCoincident;
869   aCoincident.insert(thePointID);
870
871   // Check whether one of coincident points is out-of-group
872   std::set<Slvs_hEntity>::const_iterator aCoincIt = aCoincident.begin();
873   for (; aCoincIt != aCoincident.end(); ++aCoincIt) {
874     Slvs_Entity aPoint = getEntity(*aCoincIt);
875     if (aPoint.group == SLVS_G_OUTOFGROUP)
876       return true;
877   }
878
879   // Search the Rigid constraint
880   theFixed = SLVS_C_UNKNOWN;
881   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
882   for (; aConstrIter != myConstraints.end(); aConstrIter++)
883     if (aConstrIter->type == SLVS_C_WHERE_DRAGGED &&
884         aCoincident.find(aConstrIter->ptA) != aCoincident.end()) {
885       theFixed = aConstrIter->h;
886       if (aConstrIter->ptA == thePointID)
887         return true;
888     }
889   if (theFixed != SLVS_C_UNKNOWN)
890     return true;
891
892   if (theAccurate) {
893     // Try to find the fixed entity which uses such point or its coincidence
894     std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
895     for (; anEntIter != myEntities.end(); anEntIter++) {
896       for (int i = 0; i < 4; i++) {
897         Slvs_hEntity aPt = anEntIter->point[i];
898         if (aPt != SLVS_E_UNKNOWN &&
899             (aPt == thePointID || aCoincident.find(aPt) != aCoincident.end())) {
900           if (isEntityFixed(anEntIter->h, true))
901             return true;
902         }
903       }
904     }
905   }
906   return SLVS_E_UNKNOWN;
907 }
908
909 bool SolveSpaceSolver_Storage::isEntityFixed(const Slvs_hEntity& theEntityID, bool theAccurate) const
910 {
911   int aPos = Search(theEntityID, myEntities);
912   if (aPos < 0 || aPos >= (int)myEntities.size())
913     return false;
914
915   // Firstly, find how many points are under Rigid constraint
916   int aNbFixed = 0;
917   for (int i = 0; i < 4; i++) {
918     Slvs_hEntity aPoint = myEntities[aPos].point[i];
919     if (aPoint == SLVS_E_UNKNOWN)
920       continue;
921
922     std::set<Slvs_hEntity> aCoincident;
923     aCoincident.insert(aPoint);
924
925     // Search the Rigid constraint
926     std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
927     for (; aConstrIter != myConstraints.end(); aConstrIter++)
928       if (aConstrIter->type == SLVS_C_WHERE_DRAGGED &&
929           aCoincident.find(aConstrIter->ptA) != aCoincident.end())
930         aNbFixed++;
931   }
932
933   std::list<Slvs_Constraint> aList;
934   std::list<Slvs_Constraint>::iterator anIt;
935   Slvs_hConstraint aTempID; // used in isPointFixed() method
936
937   if (myEntities[aPos].type == SLVS_E_LINE_SEGMENT) {
938     if (aNbFixed == 2)
939       return true;
940     else if (aNbFixed == 0 || !theAccurate)
941       return false;
942     // Additional check (the line may be fixed if it is used by different constraints):
943     // 1. The line is used in Equal constraint, another entity is fixed and there is a fixed point on line
944     aList = getConstraintsByType(SLVS_C_PT_ON_LINE);
945     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
946       if (anIt->entityA == theEntityID && isPointFixed(anIt->ptA, aTempID))
947         break;
948     if (anIt != aList.end()) {
949       aList = getConstraintsByType(SLVS_C_EQUAL_LENGTH_LINES);
950       aList.splice(aList.end(), getConstraintsByType(SLVS_C_EQUAL_LINE_ARC_LEN));
951       for (anIt = aList.begin(); anIt != aList.end(); anIt++)
952         if (anIt->entityA == theEntityID || anIt->entityB == theEntityID) {
953           Slvs_hEntity anOther = anIt->entityA == theEntityID ? anIt->entityB : anIt->entityA;
954           if (isEntityFixed(anOther, false))
955             return true;
956         }
957     }
958     // 2. The line is used in Parallel/Perpendicular/Vertical/Horizontal and Length constraints
959     aList = getConstraintsByType(SLVS_C_PARALLEL);
960     aList.splice(aList.end(), getConstraintsByType(SLVS_C_PERPENDICULAR));
961     aList.splice(aList.end(), getConstraintsByType(SLVS_C_VERTICAL));
962     aList.splice(aList.end(), getConstraintsByType(SLVS_C_HORIZONTAL));
963     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
964       if (anIt->entityA == theEntityID || anIt->entityB == theEntityID) {
965         Slvs_hEntity anOther = anIt->entityA == theEntityID ? anIt->entityB : anIt->entityA;
966         if (isEntityFixed(anOther, false))
967           break;
968       }
969     if (anIt != aList.end()) {
970       aList = getConstraintsByType(SLVS_C_PT_PT_DISTANCE);
971       for (anIt = aList.begin(); anIt != aList.end(); anIt++)
972         if ((anIt->ptA == myEntities[aPos].point[0] && anIt->ptB == myEntities[aPos].point[1]) ||
973             (anIt->ptA == myEntities[aPos].point[1] && anIt->ptB == myEntities[aPos].point[0]))
974           return true;
975     }
976     // 3. Another verifiers ...
977   } else if (myEntities[aPos].type == SLVS_E_CIRCLE) {
978     if (aNbFixed == 0)
979       return false;
980     // Search for Diameter constraint
981     aList = getConstraintsByType(SLVS_C_DIAMETER);
982     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
983       if (anIt->entityA == theEntityID)
984         return true;
985     if (!theAccurate)
986       return false;
987     // Additional check (the circle may be fixed if it is used by different constraints):
988     // 1. The circle is used in Equal constraint and another entity is fixed
989     aList = getConstraintsByType(SLVS_C_EQUAL_RADIUS);
990     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
991       if (anIt->entityA == theEntityID || anIt->entityB == theEntityID) {
992         Slvs_hEntity anOther = anIt->entityA == theEntityID ? anIt->entityB : anIt->entityA;
993         if (isEntityFixed(anOther, false))
994           return true;
995       }
996     // 2. Another verifiers ...
997   } else if (myEntities[aPos].type == SLVS_E_ARC_OF_CIRCLE) {
998     if (aNbFixed > 2)
999       return true;
1000     else if (aNbFixed <= 1)
1001       return false;
1002     // Search for Diameter constraint
1003     aList = getConstraintsByType(SLVS_C_DIAMETER);
1004     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
1005       if (anIt->entityA == theEntityID)
1006         return true;
1007     if (!theAccurate)
1008       return false;
1009     // Additional check (the arc may be fixed if it is used by different constraints):
1010     // 1. The arc is used in Equal constraint and another entity is fixed
1011     aList = getConstraintsByType(SLVS_C_EQUAL_RADIUS);
1012     aList.splice(aList.end(), getConstraintsByType(SLVS_C_EQUAL_LINE_ARC_LEN));
1013     for (anIt = aList.begin(); anIt != aList.end(); anIt++)
1014       if (anIt->entityA == theEntityID || anIt->entityB == theEntityID) {
1015         Slvs_hEntity anOther = anIt->entityA == theEntityID ? anIt->entityB : anIt->entityA;
1016         if (isEntityFixed(anOther, false))
1017           return true;
1018       }
1019     // 2. Another verifiers ...
1020   }
1021   return false;
1022 }
1023
1024
1025 Slvs_hConstraint SolveSpaceSolver_Storage::addConstraint(const Slvs_Constraint& theConstraint)
1026 {
1027   if (theConstraint.h > 0 && theConstraint.h <= myConstrMaxID) {
1028     // Constraint is already used, rewrite it
1029     return updateConstraint(theConstraint);
1030   }
1031
1032   Slvs_Constraint aConstraint = theConstraint;
1033
1034   // Find a constraint with same type uses same arguments to show user overconstraint situation
1035   std::vector<Slvs_Constraint>::iterator aCIt = myConstraints.begin();
1036   for (; aCIt != myConstraints.end(); aCIt++) {
1037     if (aConstraint.type != aCIt->type)
1038       continue;
1039     if (aConstraint.ptA == aCIt->ptA && aConstraint.ptB == aCIt->ptB &&
1040         aConstraint.entityA == aCIt->entityA && aConstraint.entityB == aCIt->entityB &&
1041         aConstraint.entityC == aCIt->entityC && aConstraint.entityD == aCIt->entityD)
1042       myDuplicatedConstraint = true;
1043   }
1044
1045   if (aConstraint.h > myConstrMaxID)
1046     myConstrMaxID = aConstraint.h;
1047   else
1048     aConstraint.h = ++myConstrMaxID;
1049   myConstraints.push_back(aConstraint);
1050   myNeedToResolve = true;
1051   return aConstraint.h;
1052 }
1053
1054 Slvs_hConstraint SolveSpaceSolver_Storage::updateConstraint(const Slvs_Constraint& theConstraint)
1055 {
1056   if (theConstraint.h > 0 && theConstraint.h <= myConstrMaxID) {
1057     // Constraint already used, rewrite it
1058     int aPos = Search(theConstraint.h, myConstraints);
1059     if (aPos >= 0 && aPos < (int)myConstraints.size()) {
1060       myNeedToResolve = myNeedToResolve || IsNotEqual(myConstraints[aPos], theConstraint);
1061       myConstraints[aPos] = theConstraint;
1062       return theConstraint.h;
1063     }
1064   }
1065
1066   // Constraint is not found, add new one
1067   Slvs_Constraint aConstraint = theConstraint;
1068   aConstraint.h = 0;
1069   return addConstraint(aConstraint);
1070 }
1071
1072 bool SolveSpaceSolver_Storage::removeConstraint(const Slvs_hConstraint& theConstraintID)
1073 {
1074   bool aResult = true;
1075   int aPos = Search(theConstraintID, myConstraints);
1076   if (aPos >= 0 && aPos < (int)myConstraints.size()) {
1077     Slvs_Constraint aConstraint = myConstraints[aPos];
1078     myConstraints.erase(myConstraints.begin() + aPos);
1079     myConstrMaxID = myConstraints.empty() ? SLVS_E_UNKNOWN : myConstraints.back().h;
1080     myNeedToResolve = true;
1081
1082     // Remove all entities
1083     Slvs_hEntity anEntities[6] = {aConstraint.ptA, aConstraint.ptB,
1084         aConstraint.entityA, aConstraint.entityB,
1085         aConstraint.entityC, aConstraint.entityD};
1086     for (int i = 0; i < 6; i++)
1087       if (anEntities[i] != SLVS_E_UNKNOWN)
1088         aResult = removeEntity(anEntities[i]) && aResult;
1089     // remove temporary fixed point, if available
1090     if (myFixed == theConstraintID)
1091       myFixed = SLVS_E_UNKNOWN;
1092     if (myDuplicatedConstraint) {
1093       // Check the duplicated constraints are still available
1094       myDuplicatedConstraint = false;
1095       std::vector<Slvs_Constraint>::const_iterator anIt1 = myConstraints.begin();
1096       std::vector<Slvs_Constraint>::const_iterator anIt2 = myConstraints.begin();
1097       for (; anIt1 != myConstraints.end() && !myDuplicatedConstraint; anIt1++)
1098         for (anIt2 = anIt1+1; anIt2 != myConstraints.end() && !myDuplicatedConstraint; anIt2++) {
1099           if (anIt1->type != anIt2->type)
1100             continue;
1101           if (anIt1->ptA == anIt2->ptA && anIt1->ptB == anIt2->ptB &&
1102               anIt1->entityA == anIt2->entityA && anIt1->entityB == anIt2->entityB &&
1103               anIt1->entityC == anIt2->entityC && anIt1->entityD == anIt2->entityD)
1104             myDuplicatedConstraint = true;
1105         }
1106     }
1107   }
1108   return aResult;
1109 }
1110
1111 const Slvs_Constraint& SolveSpaceSolver_Storage::getConstraint(const Slvs_hConstraint& theConstraintID) const
1112 {
1113   int aPos = Search(theConstraintID, myConstraints);
1114   if (aPos >= 0 && aPos < (int)myConstraints.size())
1115     return myConstraints[aPos];
1116
1117   // Constraint is not found, return empty object
1118   static Slvs_Constraint aDummy;
1119   aDummy.h = 0;
1120   return aDummy;
1121 }
1122
1123 std::list<Slvs_Constraint> SolveSpaceSolver_Storage::getConstraintsByType(int theConstraintType) const
1124 {
1125   std::list<Slvs_Constraint> aResult;
1126   std::vector<Slvs_Constraint>::const_iterator aCIter = myConstraints.begin();
1127   for (; aCIter != myConstraints.end(); aCIter++)
1128     if (aCIter->type == theConstraintType)
1129       aResult.push_back(*aCIter);
1130   return aResult;
1131 }
1132
1133
1134 void SolveSpaceSolver_Storage::addConstraintWhereDragged(const Slvs_hConstraint& theConstraintID)
1135 {
1136   if (myFixed != SLVS_E_UNKNOWN)
1137     return; // the point is already fixed
1138   int aPos = Search(theConstraintID, myConstraints);
1139   if (aPos >= 0 && aPos < (int)myConstraints.size())
1140     myFixed = theConstraintID;
1141 }
1142
1143
1144 void SolveSpaceSolver_Storage::initializeSolver(SolverPtr theSolver)
1145 {
1146   std::shared_ptr<SolveSpaceSolver_Solver> aSolver =
1147       std::dynamic_pointer_cast<SolveSpaceSolver_Solver>(theSolver);
1148   if (!aSolver)
1149     return;
1150
1151   if (myConstraints.empty()) {
1152     // Adjust all arc to place their points correctly
1153     std::vector<Slvs_Entity>::const_iterator anEntIt = myEntities.begin();
1154     for (; anEntIt != myEntities.end(); ++anEntIt)
1155       if (anEntIt->type == SLVS_E_ARC_OF_CIRCLE)
1156         adjustArc(*anEntIt);
1157   }
1158
1159   aSolver->setParameters(myParameters.data(), (int)myParameters.size());
1160   aSolver->setEntities(myEntities.data(), (int)myEntities.size());
1161
1162   // Copy constraints excluding the fixed one
1163   std::vector<Slvs_Constraint> aConstraints = myConstraints;
1164   if (myFixed != SLVS_E_UNKNOWN) {
1165     Slvs_hEntity aFixedPoint = SLVS_E_UNKNOWN;
1166     std::vector<Slvs_Constraint>::iterator anIt = aConstraints.begin();
1167     for (; anIt != aConstraints.end(); anIt++)
1168       if (anIt->h == myFixed) {
1169         aFixedPoint = anIt->ptA;
1170         aConstraints.erase(anIt);
1171         break;
1172       }
1173     // set dragged parameters
1174     int aPos = Search(aFixedPoint, myEntities);
1175     aSolver->setDraggedParameters(myEntities[aPos].param);
1176   }
1177   aSolver->setConstraints(aConstraints.data(), (int)aConstraints.size());
1178 }
1179
1180
1181 bool SolveSpaceSolver_Storage::isEqual(
1182     const Slvs_hEntity& thePoint1, const Slvs_hEntity& thePoint2) const
1183 {
1184   // Precise checking of coincidence: verify that points have equal coordinates
1185   int aEnt1Pos = Search(thePoint1, myEntities);
1186   int aEnt2Pos = Search(thePoint2, myEntities);
1187   if (aEnt1Pos >= 0 && aEnt1Pos < (int)myEntities.size() &&
1188       aEnt2Pos >= 0 && aEnt2Pos < (int)myEntities.size()) {
1189     double aDist[2];
1190     int aParamPos;
1191     for (int i = 0; i < 2; i++) {
1192       aParamPos = Search(myEntities[aEnt1Pos].param[i], myParameters);
1193       aDist[i] = myParameters[aParamPos].val;
1194       aParamPos = Search(myEntities[aEnt2Pos].param[i], myParameters);
1195       aDist[i] -= myParameters[aParamPos].val;
1196     }
1197     if (aDist[0] * aDist[0] + aDist[1] * aDist[1] < tolerance * tolerance)
1198       return true;
1199   }
1200   return false;
1201 }
1202
1203
1204 std::vector<Slvs_hConstraint> SolveSpaceSolver_Storage::fixEntity(const Slvs_hEntity& theEntity)
1205 {
1206   std::vector<Slvs_hConstraint> aNewConstraints;
1207
1208   int aPos = Search(theEntity, myEntities);
1209   if (aPos >= 0 && aPos < (int)myEntities.size()) {
1210     switch (myEntities[aPos].type) {
1211     case SLVS_E_POINT_IN_2D:
1212     case SLVS_E_POINT_IN_3D:
1213       fixPoint(myEntities[aPos], aNewConstraints);
1214       break;
1215     case SLVS_E_LINE_SEGMENT:
1216       fixLine(myEntities[aPos], aNewConstraints);
1217       break;
1218     case SLVS_E_CIRCLE:
1219       fixCircle(myEntities[aPos], aNewConstraints);
1220       break;
1221     case SLVS_E_ARC_OF_CIRCLE:
1222       fixArc(myEntities[aPos], aNewConstraints);
1223       break;
1224     default:
1225       break;
1226     }
1227   }
1228
1229   return aNewConstraints;
1230 }
1231
1232 void SolveSpaceSolver_Storage::fixPoint(const Slvs_Entity& thePoint,
1233     std::vector<Slvs_hConstraint>& theCreated)
1234 {
1235   Slvs_Constraint aConstraint;
1236   Slvs_hConstraint aConstrID = SLVS_E_UNKNOWN;
1237   bool isFixed = isPointFixed(thePoint.h, aConstrID, true);
1238   bool isForceUpdate = (isFixed /*&& isTemporary(aConstrID)*/);
1239   if (!isForceUpdate) { // create new constraint
1240     if (isFixed) return;
1241     aConstraint = Slvs_MakeConstraint(SLVS_E_UNKNOWN, thePoint.group, SLVS_C_WHERE_DRAGGED, thePoint.wrkpl,
1242         0.0, thePoint.h, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
1243     aConstraint.h = addConstraint(aConstraint);
1244     theCreated.push_back(aConstraint.h);
1245   } else { // update already existent constraint
1246     if (!isFixed || aConstrID == SLVS_E_UNKNOWN)
1247       return;
1248     int aPos = Search(aConstrID, myConstraints);
1249     if (aPos >= 0 && aPos < (int)myConstraints.size())
1250       myConstraints[aPos].ptA = thePoint.h;
1251   }
1252 }
1253
1254 void SolveSpaceSolver_Storage::fixLine(const Slvs_Entity& theLine,
1255     std::vector<Slvs_hConstraint>& theCreated)
1256 {
1257   Slvs_Entity aPoint[2] = {
1258       getEntity(theLine.point[0]),
1259       getEntity(theLine.point[1])
1260   };
1261
1262   Slvs_Constraint anEqual;
1263   if (isAxisParallel(theLine.h)) {
1264     // Fix one point and a line length
1265     Slvs_hConstraint aFixed;
1266     if (!isPointFixed(theLine.point[0], aFixed, true) &&
1267         !isPointFixed(theLine.point[1], aFixed, true))
1268       fixPoint(aPoint[0], theCreated);
1269     if (!isUsedInEqual(theLine.h, anEqual)) {
1270       // Check the distance is not set yet
1271       std::vector<Slvs_Constraint>::const_iterator aDistIt = myConstraints.begin();
1272       for (; aDistIt != myConstraints.end(); ++aDistIt)
1273         if ((aDistIt->type == SLVS_C_PT_PT_DISTANCE) &&
1274            ((aDistIt->ptA == theLine.point[0] && aDistIt->ptB == theLine.point[1]) ||
1275             (aDistIt->ptA == theLine.point[1] && aDistIt->ptB == theLine.point[0])))
1276           return;
1277       // Calculate distance between points on the line
1278       double aCoords[4];
1279       for (int i = 0; i < 2; i++)
1280         for (int j = 0; j < 2; j++) {
1281           Slvs_Param aParam = getParameter(aPoint[i].param[j]);
1282           aCoords[2*i+j] = aParam.val;
1283         }
1284
1285       double aLength = sqrt((aCoords[2] - aCoords[0]) * (aCoords[2] - aCoords[0]) + 
1286                             (aCoords[3] - aCoords[1]) * (aCoords[3] - aCoords[1]));
1287       // fix line length
1288       Slvs_Constraint aDistance = Slvs_MakeConstraint(SLVS_E_UNKNOWN, theLine.group,
1289           SLVS_C_PT_PT_DISTANCE, theLine.wrkpl, aLength,
1290           theLine.point[0], theLine.point[1], SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
1291       aDistance.h = addConstraint(aDistance);
1292       theCreated.push_back(aDistance.h);
1293     }
1294     return;
1295   }
1296   else if (isUsedInEqual(theLine.h, anEqual)) {
1297     // Check another entity of Equal is already fixed
1298     Slvs_hEntity anOtherEntID = anEqual.entityA == theLine.h ? anEqual.entityB : anEqual.entityA;
1299     if (isEntityFixed(anOtherEntID, true)) {
1300       // Fix start point of the line (if end point is not fixed yet) ...
1301       Slvs_hConstraint anEndFixedID = SLVS_E_UNKNOWN;
1302       bool isFixed = isPointFixed(theLine.point[1], anEndFixedID, true);
1303       if (isFixed == SLVS_E_UNKNOWN)
1304         fixPoint(aPoint[0], theCreated);
1305       // ...  and create fixed point lying on this line
1306       Slvs_hEntity aPointToCopy = anEndFixedID == SLVS_E_UNKNOWN ? theLine.point[1] : theLine.point[0];
1307       // Firstly, search already fixed point on line
1308       bool isPonLineFixed = false;
1309       Slvs_hEntity aFixedPoint;
1310       std::vector<Slvs_Constraint>::const_iterator aPLIter = myConstraints.begin();
1311       for (; aPLIter != myConstraints.end() && !isPonLineFixed; ++aPLIter)
1312         if (aPLIter->type == SLVS_C_PT_ON_LINE && aPLIter->entityA == theLine.h) {
1313           isPonLineFixed = isPointFixed(aPLIter->ptA, anEndFixedID);
1314           aFixedPoint = aPLIter->ptA;
1315         }
1316
1317       if (isPonLineFixed) { // update existent constraint
1318         copyEntity(aPointToCopy, aFixedPoint);
1319       } else { // create new constraint
1320         Slvs_hEntity aCopied = copyEntity(aPointToCopy);
1321         Slvs_Constraint aPonLine = Slvs_MakeConstraint(SLVS_E_UNKNOWN, theLine.group, SLVS_C_PT_ON_LINE,
1322             theLine.wrkpl, 0.0, aCopied, SLVS_E_UNKNOWN, theLine.h, SLVS_E_UNKNOWN);
1323         aPonLine.h = addConstraint(aPonLine);
1324         theCreated.push_back(aPonLine.h);
1325         fixPoint(getEntity(aCopied), theCreated);
1326       }
1327       return;
1328     }
1329   }
1330
1331   // Fix both points
1332   for (int i = 0; i < 2; i++)
1333     fixPoint(aPoint[i], theCreated);
1334 }
1335
1336 void SolveSpaceSolver_Storage::fixCircle(const Slvs_Entity& theCircle,
1337     std::vector<Slvs_hConstraint>& theCreated)
1338 {
1339   bool isFixRadius = true;
1340   // Verify the arc is under Equal constraint
1341   Slvs_Constraint anEqual;
1342   if (isUsedInEqual(theCircle.h, anEqual)) {
1343     // Check another entity of Equal is already fixed
1344     Slvs_hEntity anOtherEntID = anEqual.entityA == theCircle.h ? anEqual.entityB : anEqual.entityA;
1345     if (isEntityFixed(anOtherEntID, true))
1346       isFixRadius = false;
1347   }
1348
1349   fixPoint(getEntity(theCircle.point[0]), theCreated);
1350
1351   if (isFixRadius) {
1352     // Search the radius is already fixed
1353     std::vector<Slvs_Constraint>::const_iterator aDiamIter = myConstraints.begin();
1354     for (; aDiamIter != myConstraints.end(); ++aDiamIter)
1355       if (aDiamIter->type == SLVS_C_DIAMETER && aDiamIter->entityA == theCircle.h)
1356         return;
1357
1358     // Fix radius of a circle
1359     const Slvs_Entity& aRadEnt = getEntity(theCircle.distance);
1360     double aRadius = getParameter(aRadEnt.param[0]).val;
1361     Slvs_Constraint aFixedR = Slvs_MakeConstraint(SLVS_E_UNKNOWN, theCircle.group, SLVS_C_DIAMETER,
1362         theCircle.wrkpl, aRadius * 2.0, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, theCircle.h, SLVS_E_UNKNOWN);
1363     aFixedR.h = addConstraint(aFixedR);
1364     theCreated.push_back(aFixedR.h);
1365   }
1366 }
1367
1368 void SolveSpaceSolver_Storage::fixArc(const Slvs_Entity& theArc,
1369     std::vector<Slvs_hConstraint>& theCreated)
1370 {
1371   Slvs_Entity aPoint[3] = {
1372       getEntity(theArc.point[0]),
1373       getEntity(theArc.point[1]),
1374       getEntity(theArc.point[2])
1375   };
1376
1377   bool isFixRadius = true;
1378   std::list<Slvs_Entity> aPointsToFix;
1379   aPointsToFix.push_back(aPoint[1]);
1380   aPointsToFix.push_back(aPoint[2]);
1381
1382   // Verify the arc is under Equal constraint
1383   Slvs_Constraint anEqual;
1384   if (isUsedInEqual(theArc.h, anEqual)) {
1385     // Check another entity of Equal is already fixed
1386     Slvs_hEntity anOtherEntID = anEqual.entityA == theArc.h ? anEqual.entityB : anEqual.entityA;
1387     if (isEntityFixed(anOtherEntID, true)) {
1388       isFixRadius = false;
1389       Slvs_Entity anOtherEntity = getEntity(anOtherEntID);
1390       if (anOtherEntity.type == SLVS_E_LINE_SEGMENT) {
1391         aPointsToFix.pop_back();
1392         aPointsToFix.push_back(aPoint[0]);
1393       }
1394     }
1395   }
1396
1397   Slvs_hConstraint aConstrID;
1398   int aNbPointsToFix = 2; // number of fixed points for the arc
1399   if (isPointFixed(theArc.point[0], aConstrID, true))
1400     aNbPointsToFix--;
1401
1402   double anArcPoints[3][2];
1403   for (int i = 0; i < 3; i++) {
1404     const Slvs_Entity& aPointOnArc = getEntity(theArc.point[i]);
1405     for (int j = 0; j < 2; j++)
1406       anArcPoints[i][j] = getParameter(aPointOnArc.param[j]).val;
1407   }
1408
1409   // Radius of the arc
1410   std::shared_ptr<GeomAPI_Pnt2d> aCenter(new GeomAPI_Pnt2d(anArcPoints[0][0], anArcPoints[0][1]));
1411   std::shared_ptr<GeomAPI_Pnt2d> aStart(new GeomAPI_Pnt2d(anArcPoints[1][0], anArcPoints[1][1]));
1412   double aRadius = aCenter->distance(aStart);
1413
1414   // Update end point of the arc to be on a curve
1415   std::shared_ptr<GeomAPI_Pnt2d> anEnd(new GeomAPI_Pnt2d(anArcPoints[2][0], anArcPoints[2][1]));
1416   double aDistance = anEnd->distance(aCenter);
1417   std::shared_ptr<GeomAPI_XY> aDir = anEnd->xy()->decreased(aCenter->xy());
1418   if (aDistance < tolerance)
1419     aDir = aStart->xy()->decreased(aCenter->xy())->multiplied(-1.0);
1420   else
1421     aDir = aDir->multiplied(aRadius / aDistance);
1422   double xy[2] = {aCenter->x() + aDir->x(), aCenter->y() + aDir->y()};
1423   const Slvs_Entity& aEndPoint = getEntity(theArc.point[2]);
1424   for (int i = 0; i < 2; i++) {
1425     Slvs_Param aParam = getParameter(aEndPoint.param[i]);
1426     aParam.val = xy[i];
1427     updateParameter(aParam);
1428   }
1429
1430   std::list<Slvs_Entity>::iterator aPtIt = aPointsToFix.begin();
1431   for (; aNbPointsToFix > 0; aPtIt++, aNbPointsToFix--)
1432     fixPoint(*aPtIt, theCreated);
1433
1434   if (isFixRadius) {
1435     // Fix radius of the arc
1436     bool isExists = false;
1437     std::vector<Slvs_Constraint>::iterator anIt = myConstraints.begin();
1438     for (; anIt != myConstraints.end() && !isExists; ++anIt)
1439       if (anIt->type == SLVS_C_DIAMETER && anIt->entityA == theArc.h)
1440         isExists = true;
1441     if (!isExists) {
1442       Slvs_Constraint aFixedR = Slvs_MakeConstraint(SLVS_E_UNKNOWN, theArc.group, SLVS_C_DIAMETER,
1443           theArc.wrkpl, aRadius * 2.0, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, theArc.h, SLVS_E_UNKNOWN);
1444       aFixedR.h = addConstraint(aFixedR);
1445       theCreated.push_back(aFixedR.h);
1446     }
1447   }
1448 }
1449
1450
1451 bool SolveSpaceSolver_Storage::isAxisParallel(const Slvs_hEntity& theEntity) const
1452 {
1453   std::vector<Slvs_Constraint>::const_iterator anIter = myConstraints.begin();
1454   for (; anIter != myConstraints.end(); anIter++)
1455     if ((anIter->type == SLVS_C_HORIZONTAL || anIter->type == SLVS_C_VERTICAL) && 
1456         anIter->entityA == theEntity)
1457       return true;
1458   return false;
1459 }
1460
1461 bool SolveSpaceSolver_Storage::isUsedInEqual(
1462     const Slvs_hEntity& theEntity, Slvs_Constraint& theEqual) const
1463 {
1464   // Check the entity is used in Equal constraint
1465   std::vector<Slvs_Constraint>::const_iterator anEqIter = myConstraints.begin();
1466   for (; anEqIter != myConstraints.end(); anEqIter++)
1467     if ((anEqIter->type == SLVS_C_EQUAL_LENGTH_LINES ||
1468          anEqIter->type == SLVS_C_EQUAL_LINE_ARC_LEN ||
1469          anEqIter->type == SLVS_C_EQUAL_RADIUS) &&
1470        (anEqIter->entityA == theEntity || anEqIter->entityB == theEntity)) {
1471       theEqual = *anEqIter;
1472       return true;
1473     }
1474   return false;
1475 }
1476
1477
1478 bool SolveSpaceSolver_Storage::remove(ConstraintWrapperPtr theConstraint)
1479 {
1480   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
1481       std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
1482
1483   // verify whether the constraint has duplicated
1484   SameConstraintMap::iterator anEqIt = myEqualConstraints.begin();
1485   for (; anEqIt != myEqualConstraints.end(); ++anEqIt)
1486     if (anEqIt->find(aConstraint) != anEqIt->end()) {
1487       anEqIt->erase(aConstraint);
1488       break;
1489     }
1490   if (anEqIt != myEqualConstraints.end())
1491     return true;
1492
1493   bool isFullyRemoved = removeConstraint((Slvs_hConstraint)aConstraint->id());
1494   return SketchSolver_Storage::remove(theConstraint) && isFullyRemoved;
1495 }
1496
1497 bool SolveSpaceSolver_Storage::remove(EntityWrapperPtr theEntity)
1498 {
1499   if (!theEntity)
1500     return false;
1501
1502   std::shared_ptr<SolveSpaceSolver_EntityWrapper> anEntity = 
1503         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theEntity);
1504   bool isFullyRemoved = removeEntity((Slvs_hEntity)anEntity->id());
1505   return SketchSolver_Storage::remove(theEntity) && isFullyRemoved;
1506 }
1507
1508 bool SolveSpaceSolver_Storage::remove(ParameterWrapperPtr theParameter)
1509 {
1510   return removeParameter((Slvs_hParam)theParameter->id());
1511 }
1512
1513
1514 void SolveSpaceSolver_Storage::refresh(bool theFixedOnly) const
1515 {
1516   //blockEvents(true);
1517
1518   std::map<AttributePtr, EntityWrapperPtr>::const_iterator anIt = myAttributeMap.begin();
1519   std::list<ParameterWrapperPtr> aParams;
1520   std::list<ParameterWrapperPtr>::const_iterator aParIt;
1521   for (; anIt != myAttributeMap.end(); ++anIt) {
1522     // the external feature always should keep the up to date values, so, 
1523     // refresh from the solver is never needed
1524     if (anIt->first.get()) {
1525       std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
1526         std::dynamic_pointer_cast<SketchPlugin_Feature>(anIt->first->owner());
1527       if (aSketchFeature.get() && aSketchFeature->isExternal())
1528         continue;
1529     }
1530
1531     // update parameter wrappers and obtain values of attributes
1532     aParams = anIt->second->parameters();
1533     double aCoords[3];
1534     bool isUpd[3] = {false};
1535     int i = 0;
1536     for (aParIt = aParams.begin(); i < 3 && aParIt != aParams.end(); ++aParIt, ++i) {
1537       std::shared_ptr<SolveSpaceSolver_ParameterWrapper> aWrapper = 
1538           std::dynamic_pointer_cast<SolveSpaceSolver_ParameterWrapper>(*aParIt);
1539       if (!theFixedOnly || aWrapper->group() == GID_OUTOFGROUP || aWrapper->isParametric()) {
1540         aWrapper->changeParameter().val = getParameter((Slvs_hParam)aWrapper->id()).val;
1541         aCoords[i] = aWrapper->value();
1542         isUpd[i] = true;
1543       }
1544     }
1545     if (!isUpd[0] && !isUpd[1] && !isUpd[2])
1546       continue; // nothing is updated
1547
1548     std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
1549         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anIt->first);
1550     if (aPoint2D) {
1551       if ((isUpd[0] && fabs(aPoint2D->x() - aCoords[0]) > tolerance) ||
1552           (isUpd[1] && fabs(aPoint2D->y() - aCoords[1]) > tolerance)) {
1553         if (!isUpd[0]) aCoords[0] = aPoint2D->x();
1554         if (!isUpd[1]) aCoords[1] = aPoint2D->y();
1555         aPoint2D->setValue(aCoords[0], aCoords[1]);
1556         // Find points coincident with this one (probably not in GID_OUTOFGROUP)
1557         std::map<AttributePtr, EntityWrapperPtr>::const_iterator aLocIt =
1558             theFixedOnly ? myAttributeMap.begin() : anIt;
1559         for (++aLocIt; aLocIt != myAttributeMap.end(); ++aLocIt)
1560           if (anIt->second->id() == aLocIt->second->id()) {
1561             aPoint2D = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aLocIt->first);
1562             aPoint2D->setValue(aCoords[0], aCoords[1]);
1563           }
1564       }
1565       continue;
1566     }
1567     AttributeDoublePtr aScalar = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(anIt->first);
1568     if (aScalar) {
1569       if (isUpd[0] && fabs(aScalar->value() - aCoords[0]) > tolerance)
1570         aScalar->setValue(aCoords[0]);
1571       continue;
1572     }
1573     std::shared_ptr<GeomDataAPI_Point> aPoint =
1574         std::dynamic_pointer_cast<GeomDataAPI_Point>(anIt->first);
1575     if (aPoint) {
1576       if ((isUpd[0] && fabs(aPoint->x() - aCoords[0]) > tolerance) ||
1577           (isUpd[1] && fabs(aPoint->y() - aCoords[1]) > tolerance) ||
1578           (isUpd[2] && fabs(aPoint->z() - aCoords[2]) > tolerance))
1579         if (!isUpd[0]) aCoords[0] = aPoint->x();
1580         if (!isUpd[1]) aCoords[1] = aPoint->y();
1581         if (!isUpd[2]) aCoords[2] = aPoint->z();
1582         aPoint->setValue(aCoords[0], aCoords[1], aCoords[2]);
1583       continue;
1584     }
1585   }
1586
1587   //blockEvents(false);
1588 }
1589
1590 void SolveSpaceSolver_Storage::verifyFixed()
1591 {
1592   std::map<AttributePtr, EntityWrapperPtr>::iterator anAttrIt = myAttributeMap.begin();
1593   for (; anAttrIt != myAttributeMap.end(); ++anAttrIt) {
1594     const std::list<ParameterWrapperPtr>& aParameters = anAttrIt->second->parameters();
1595     std::list<ParameterWrapperPtr>::const_iterator aParIt = aParameters.begin();
1596     for (; aParIt != aParameters.end(); ++aParIt)
1597       if ((*aParIt)->group() == GID_OUTOFGROUP) {
1598         Slvs_Param aParam = getParameter((Slvs_hParam)(*aParIt)->id());
1599         if (aParam.group != (Slvs_hParam)GID_OUTOFGROUP) {
1600           aParam.group = (Slvs_hParam)GID_OUTOFGROUP;
1601           updateParameter(aParam);
1602         }
1603       }
1604   }
1605 }
1606
1607
1608 void SolveSpaceSolver_Storage::adjustArc(const Slvs_Entity& theArc)
1609 {
1610   double anArcPoints[3][2];
1611   double aDist[3] = {0.0};
1612   bool isFixed[3] = {false};
1613   for (int i = 0; i < 3; ++i) {
1614     Slvs_Entity aPoint = getEntity(theArc.point[i]);
1615     isFixed[i] = (aPoint.group != (Slvs_hGroup)myGroupID);
1616     anArcPoints[i][0] = getParameter(aPoint.param[0]).val;
1617     anArcPoints[i][1] = getParameter(aPoint.param[1]).val;
1618     if (i > 0) {
1619       anArcPoints[i][0] -= anArcPoints[0][0];
1620       anArcPoints[i][1] -= anArcPoints[0][1];
1621       aDist[i] = sqrt(anArcPoints[i][0] * anArcPoints[i][0] + 
1622                       anArcPoints[i][1] * anArcPoints[i][1]);
1623     }
1624   }
1625
1626   if (fabs(aDist[1] - aDist[2]) < tolerance)
1627     return;
1628
1629   int anInd = 2;
1630   while (anInd > 0 && isFixed[anInd])
1631     --anInd;
1632   if (anInd < 1)
1633     return; // adjust only start or end point of the arc
1634
1635   anArcPoints[anInd][0] /= aDist[anInd];
1636   anArcPoints[anInd][1] /= aDist[anInd];
1637
1638   Slvs_Entity aPoint = getEntity(theArc.point[anInd]);
1639   for (int i = 0; i < 2; ++i) {
1640     Slvs_Param aParam = getParameter(aPoint.param[i]);
1641     aParam.val = anArcPoints[0][i] + aDist[3-anInd] * anArcPoints[anInd][i];
1642     updateParameter(aParam);
1643   }
1644 }
1645
1646
1647
1648
1649
1650
1651
1652 // ========================================================
1653 // =========      Auxiliary functions       ===============
1654 // ========================================================
1655
1656 template<typename T>
1657 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1658 {
1659   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1660   int aVecSize = theEntities.size();
1661   if (theEntities.empty())
1662     return 1;
1663   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1664     aResIndex--;
1665   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1666     aResIndex++;
1667   if (aResIndex == -1 || (aResIndex < aVecSize && theEntities[aResIndex].h != theEntityID))
1668     aResIndex = aVecSize;
1669   return aResIndex;
1670 }
1671
1672 bool IsNotEqual(const Slvs_Param& theParam1, const Slvs_Param& theParam2)
1673 {
1674   return fabs(theParam1.val - theParam2.val) > tolerance;
1675 }
1676
1677 bool IsNotEqual(const Slvs_Entity& theEntity1, const Slvs_Entity& theEntity2)
1678 {
1679   int i = 0;
1680   for (; theEntity1.param[i] != 0 && i < 4; i++)
1681     if (theEntity1.param[i] != theEntity2.param[i])
1682       return true;
1683   i = 0;
1684   for (; theEntity1.point[i] != 0 && i < 4; i++)
1685     if (theEntity1.point[i] != theEntity2.point[i])
1686       return true;
1687   return false;
1688 }
1689
1690 bool IsNotEqual(const Slvs_Constraint& theConstraint1, const Slvs_Constraint& theConstraint2)
1691 {
1692   return theConstraint1.ptA != theConstraint2.ptA ||
1693          theConstraint1.ptB != theConstraint2.ptB ||
1694          theConstraint1.entityA != theConstraint2.entityA ||
1695          theConstraint1.entityB != theConstraint2.entityB ||
1696          theConstraint1.entityC != theConstraint2.entityC ||
1697          theConstraint1.entityD != theConstraint2.entityD ||
1698          fabs(theConstraint1.valA - theConstraint2.valA) > tolerance;
1699 }