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