Salome HOME
Fix problems happened during unit testing
[modules/shaper.git] / src / SketchSolver / SolveSpaceSolver / SolveSpaceSolver_Builder.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SolveSpaceSolver_Builder.cpp
4 // Created: 25 Mar 2015
5 // Author:  Artem ZHIDKOV
6
7 #include <SolveSpaceSolver_Builder.h>
8 #include <SolveSpaceSolver_Solver.h>
9 #include <SolveSpaceSolver_Storage.h>
10 #include <SolveSpaceSolver_ParameterWrapper.h>
11 #include <SolveSpaceSolver_EntityWrapper.h>
12 #include <SolveSpaceSolver_ConstraintWrapper.h>
13 #include <SolveSpaceSolver_ConstraintType.h>
14
15 #include <SketchSolver_Manager.h>
16
17 #include <GeomAPI_Angle2d.h>
18 #include <GeomAPI_Dir2d.h>
19 #include <GeomAPI_Pnt2d.h>
20 #include <GeomAPI_XY.h>
21 #include <GeomDataAPI_Dir.h>
22 #include <GeomDataAPI_Point.h>
23 #include <GeomDataAPI_Point2D.h>
24 #include <ModelAPI_Attribute.h>
25 #include <ModelAPI_AttributeRefAttr.h>
26
27 #include <SketchPlugin_Arc.h>
28 #include <SketchPlugin_Circle.h>
29 #include <SketchPlugin_Line.h>
30 #include <SketchPlugin_Point.h>
31 #include <SketchPlugin_IntersectionPoint.h>
32 #include <SketchPlugin_ConstraintAngle.h>
33
34 #include <math.h>
35
36
37 static EntityWrapperPtr createLine(FeaturePtr theFeature,
38                                    const std::list<EntityWrapperPtr>& theAttributes,
39                                    const GroupID& theGroupID,
40                                    const EntityID& theSketchID);
41 static EntityWrapperPtr createCircle(FeaturePtr theFeature,
42                                      const std::list<EntityWrapperPtr>& theAttributes,
43                                      const GroupID& theGroupID,
44                                      const EntityID& theSketchID);
45 static EntityWrapperPtr createArc(FeaturePtr theFeature,
46                                   const std::list<EntityWrapperPtr>& theAttributes,
47                                   const GroupID& theGroupID,
48                                   const EntityID& theSketchID);
49
50 /// \brief Set flags of constraint to identify which points are coincident in the Tangency
51 ///        (for more information, see SolveSpace documentation)
52 static void adjustTangency(ConstraintWrapperPtr theConstraint);
53 /// \brief Set flags for angle constraint
54 static void adjustAngle(ConstraintWrapperPtr theConstraint);
55 /// \brief Update mirror points
56 static void adjustMirror(ConstraintWrapperPtr theConstraint);
57 /// \brief Update a sign of the point-line distance constraint
58 static void adjustPtLineDistance(ConstraintWrapperPtr theConstraint);
59
60 /// \brief Transform points to be symmetric regarding to the mirror line
61 static void makeMirrorPoints(EntityWrapperPtr theOriginal,
62                              EntityWrapperPtr theMirrored,
63                              EntityWrapperPtr theMirrorLine);
64
65
66
67 // Initialization of constraint builder self pointer
68 BuilderPtr SolveSpaceSolver_Builder::mySelf = SolveSpaceSolver_Builder::getInstance();
69
70 BuilderPtr SolveSpaceSolver_Builder::getInstance()
71 {
72   if (!mySelf) {
73     mySelf = BuilderPtr(new SolveSpaceSolver_Builder);
74     SketchSolver_Manager::instance()->setBuilder(mySelf);
75   }
76   return mySelf;
77 }
78
79 StoragePtr SolveSpaceSolver_Builder::createStorage(const GroupID& theGroup) const
80 {
81   return StoragePtr(new SolveSpaceSolver_Storage(theGroup));
82 }
83
84 SolverPtr SolveSpaceSolver_Builder::createSolver() const
85 {
86   return SolverPtr(new SolveSpaceSolver_Solver);
87 }
88
89
90 std::list<ConstraintWrapperPtr> SolveSpaceSolver_Builder::createConstraint(
91     ConstraintPtr theConstraint,
92     const GroupID& theGroupID,
93     const EntityID& theSketchID,
94     const SketchSolver_ConstraintType& theType,
95     const double& theValue,
96     const EntityWrapperPtr& thePoint1,
97     const EntityWrapperPtr& thePoint2,
98     const EntityWrapperPtr& theEntity1,
99     const EntityWrapperPtr& theEntity2) const
100 {
101   if (theType == CONSTRAINT_SYMMETRIC)
102     return createMirror(theConstraint, theGroupID, theSketchID,
103                         thePoint1, thePoint2, theEntity1);
104   else if (theType == CONSTRAINT_TANGENT_CIRCLE_LINE) {
105     // replace by distance from center of circle to the line
106     const std::list<EntityWrapperPtr>& aSubs = theEntity1->subEntities();
107     EntityWrapperPtr aCenter = aSubs.front();
108     AttributeDoublePtr aRadius = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
109         aSubs.back()->baseAttribute());
110     return createConstraint(theConstraint, theGroupID, theSketchID,
111         CONSTRAINT_PT_LINE_DISTANCE, aRadius->value(), aCenter, EntityWrapperPtr(), theEntity2);
112   }
113   else if (theType == CONSTRAINT_COLLINEAR) {
114     // replace by two constraints point-on-line
115     std::list<ConstraintWrapperPtr> aConstraints;
116     const std::list<EntityWrapperPtr>& aSubs1 = theEntity1->subEntities();
117     const std::list<EntityWrapperPtr>& aSubs2 = theEntity2->subEntities();
118     std::list<EntityWrapperPtr>::const_iterator anIt1, anIt2;
119     for (anIt2 = aSubs2.begin(); anIt2 != aSubs2.end(); ++anIt2) {
120       for (anIt1 = aSubs1.begin(); anIt1 != aSubs1.end(); ++anIt1)
121         if ((*anIt1)->id() == (*anIt2)->id())
122           break;
123       if (anIt1 != aSubs1.end())
124         continue; // the lines have coincident point
125
126       std::list<ConstraintWrapperPtr> aC = createConstraint(theConstraint, theGroupID,
127           theSketchID, CONSTRAINT_PT_ON_LINE, theValue, *anIt2, EntityWrapperPtr(), theEntity1);
128       aConstraints.insert(aConstraints.end(), aC.begin(), aC.end());
129     }
130     return aConstraints;
131   }
132
133   int aType = ConstraintType::toSolveSpace(theType);
134   if (aType == SLVS_C_UNKNOWN)
135     return std::list<ConstraintWrapperPtr>();
136
137   Slvs_hEntity aSlvsEntities[4] = {SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN};
138   EntityWrapperPtr anOriginal[4] = {thePoint1, thePoint2, theEntity1, theEntity2};
139   std::list<EntityWrapperPtr> aConstrAttrList; // to be filled
140   for (int i = 0; i < 4; ++i) {
141     if (!anOriginal[i])
142       continue;
143     aSlvsEntities[i] = (Slvs_hEntity)anOriginal[i]->id();
144     if (aSlvsEntities[i] == SLVS_E_UNKNOWN)
145       return std::list<ConstraintWrapperPtr>(); // entity is not added into a storage, constraint can not be created
146     aConstrAttrList.push_back(anOriginal[i]);
147   }
148
149   Slvs_Constraint aConstraint = Slvs_MakeConstraint(
150       SLVS_C_UNKNOWN, (Slvs_hGroup)theGroupID, aType, (Slvs_hEntity)theSketchID,
151       theValue, aSlvsEntities[0], aSlvsEntities[1], aSlvsEntities[2], aSlvsEntities[3]);
152   ConstraintWrapperPtr aResult(new SolveSpaceSolver_ConstraintWrapper(theConstraint, aConstraint));
153   aResult->setGroup(theGroupID);
154   aResult->setValue(theValue);
155   aResult->setEntities(aConstrAttrList);
156   adjustConstraint(aResult);
157
158   return std::list<ConstraintWrapperPtr>(1, aResult);
159 }
160
161 std::list<ConstraintWrapperPtr> SolveSpaceSolver_Builder::createConstraint(
162     ConstraintPtr theConstraint,
163     const GroupID& theGroupID,
164     const EntityID& theSketchID,
165     const SketchSolver_ConstraintType& theType,
166     const double& theValue,
167     const bool theFullValue,
168     const EntityWrapperPtr& thePoint1,
169     const EntityWrapperPtr& thePoint2,
170     const std::list<EntityWrapperPtr>& theTrsfEnt) const
171 {
172   if (theType != CONSTRAINT_MULTI_ROTATION && theType != CONSTRAINT_MULTI_TRANSLATION)
173     return std::list<ConstraintWrapperPtr>();
174
175   int aType = ConstraintType::toSolveSpace(theType);
176   if (aType == SLVS_C_UNKNOWN)
177     return std::list<ConstraintWrapperPtr>();
178
179   Slvs_Constraint aConstraint =
180       Slvs_MakeConstraint(SLVS_C_UNKNOWN, (Slvs_hGroup)theGroupID, aType, (Slvs_hEntity)theSketchID,
181       theValue, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
182
183   std::list<EntityWrapperPtr> aConstrAttrList = theTrsfEnt;
184   if (thePoint2)
185     aConstrAttrList.push_front(thePoint2);
186   aConstrAttrList.push_front(thePoint1);
187
188   ConstraintWrapperPtr aResult(new SolveSpaceSolver_ConstraintWrapper(theConstraint, aConstraint));
189   aResult->setGroup(theGroupID);
190   aResult->setValue(theValue);
191   aResult->setIsFullValue(theFullValue);
192   aResult->setEntities(aConstrAttrList);
193   return std::list<ConstraintWrapperPtr>(1, aResult);
194 }
195
196
197 std::list<ConstraintWrapperPtr> SolveSpaceSolver_Builder::createMirror(
198     ConstraintPtr theConstraint,
199     const GroupID& theGroupID,
200     const EntityID& theSketchID,
201     const EntityWrapperPtr& theEntity1,
202     const EntityWrapperPtr& theEntity2,
203     const EntityWrapperPtr& theMirrorLine) const
204 {
205   Slvs_Constraint aConstraint;
206   std::list<ConstraintWrapperPtr> aResult;
207   std::list<EntityWrapperPtr> aConstrAttrList;
208   if (theEntity1->type() == ENTITY_POINT) {
209     makeMirrorPoints(theEntity1, theEntity2, theMirrorLine);
210
211     aConstraint = Slvs_MakeConstraint(
212         SLVS_E_UNKNOWN, (Slvs_hGroup)theGroupID, SLVS_C_SYMMETRIC_LINE, (Slvs_hEntity)theSketchID,
213         0.0, (Slvs_hEntity)theEntity1->id(), (Slvs_hEntity)theEntity2->id(),
214         (Slvs_hEntity)theMirrorLine->id(), SLVS_E_UNKNOWN);
215
216     aConstrAttrList.push_back(theEntity1);
217     aConstrAttrList.push_back(theEntity2);
218     aConstrAttrList.push_back(theMirrorLine);
219
220     ConstraintWrapperPtr aWrapper(new SolveSpaceSolver_ConstraintWrapper(
221         theConstraint, aConstraint));
222     aWrapper->setGroup(theGroupID);
223     aWrapper->setEntities(aConstrAttrList);
224     aResult.push_back(aWrapper);
225   }
226   else if (theEntity1->type() == ENTITY_LINE) {
227     const std::list<EntityWrapperPtr>& aPoints1 = theEntity1->subEntities();
228     const std::list<EntityWrapperPtr>& aPoints2 = theEntity2->subEntities();
229     std::list<EntityWrapperPtr>::const_iterator anIt1 = aPoints1.begin();
230     std::list<EntityWrapperPtr>::const_iterator anIt2 = aPoints2.begin();
231     for (; anIt1 != aPoints1.end() && anIt2 != aPoints2.end(); ++anIt1, ++anIt2) {
232       std::list<ConstraintWrapperPtr> aMrrList =
233           createMirror(theConstraint, theGroupID, theSketchID, *anIt1, *anIt2, theMirrorLine);
234       aResult.insert(aResult.end(), aMrrList.begin(), aMrrList.end());
235     }
236   }
237   else if (theEntity1->type() == ENTITY_CIRCLE) {
238     const std::list<EntityWrapperPtr>& aPoints1 = theEntity1->subEntities();
239     std::list<EntityWrapperPtr>::const_iterator anIt1 = aPoints1.begin();
240     for (; anIt1 != aPoints1.end(); ++anIt1)
241       if ((*anIt1)->type() == ENTITY_POINT)
242         break;
243     const std::list<EntityWrapperPtr>& aPoints2 = theEntity2->subEntities();
244     std::list<EntityWrapperPtr>::const_iterator anIt2 = aPoints2.begin();
245     for (; anIt2 != aPoints2.end(); ++anIt2)
246       if ((*anIt2)->type() == ENTITY_POINT)
247         break;
248
249     std::list<ConstraintWrapperPtr> aMrrList =
250         createMirror(theConstraint, theGroupID, theSketchID, *anIt1, *anIt2, theMirrorLine);
251     aResult.insert(aResult.end(), aMrrList.begin(), aMrrList.end());
252
253     // Additional constraint for equal radii
254     aMrrList = createConstraint(theConstraint, theGroupID, theSketchID, CONSTRAINT_EQUAL_RADIUS,
255         0.0, EntityWrapperPtr(), EntityWrapperPtr(), theEntity1, theEntity2);
256     aResult.insert(aResult.end(), aMrrList.begin(), aMrrList.end());
257   }
258   else if (theEntity1->type() == ENTITY_ARC) {
259     // Do not allow mirrored arc recalculate its position until coordinated of all points recalculated
260     FeaturePtr aMirrArc = theEntity2->baseFeature();
261     aMirrArc->data()->blockSendAttributeUpdated(true);
262
263     std::list<ConstraintWrapperPtr> aMrrList;
264     std::list<EntityWrapperPtr>::const_iterator anIt1 = theEntity1->subEntities().begin();
265     std::list<EntityWrapperPtr>::const_iterator anIt2 = theEntity2->subEntities().begin();
266     makeMirrorPoints(*anIt1, *anIt2, theMirrorLine);
267
268     // Workaround to avoid problems in SolveSpace.
269     // The symmetry of two arcs will be done using symmetry of three points on these arcs:
270     // start point, end point, and any other point on the arc
271     std::list<EntityWrapperPtr> aBaseArcPoints(++anIt1, theEntity1->subEntities().end());
272     std::list<EntityWrapperPtr> aMirrorArcPoints(++anIt2, theEntity2->subEntities().end());
273     // indices of points of arc, center corresponds center, first point corresponds last point
274     aMirrorArcPoints.reverse();
275
276     anIt1 = aBaseArcPoints.begin();
277     anIt2 = aMirrorArcPoints.begin();
278     for (; anIt1 != aBaseArcPoints.end(); ++anIt1, ++anIt2) {
279       aMrrList = createMirror(theConstraint, theGroupID, theSketchID, *anIt1, *anIt2, theMirrorLine);
280       aResult.insert(aResult.end(), aMrrList.begin(), aMrrList.end());
281     }
282     // Restore event sending
283     aMirrArc->data()->blockSendAttributeUpdated(false);
284   }
285   return aResult;
286 }
287
288 void SolveSpaceSolver_Builder::adjustConstraint(ConstraintWrapperPtr theConstraint) const
289 {
290   SketchSolver_ConstraintType aType = theConstraint->type();
291   // Update flags in constraints
292   if (aType == CONSTRAINT_TANGENT_ARC_ARC || aType == CONSTRAINT_TANGENT_ARC_LINE)
293     adjustTangency(theConstraint);
294   else if (aType == CONSTRAINT_ANGLE)
295     adjustAngle(theConstraint);
296   else if (aType == CONSTRAINT_SYMMETRIC)
297     adjustMirror(theConstraint);
298   else if (aType == CONSTRAINT_PT_LINE_DISTANCE)
299     adjustPtLineDistance(theConstraint);
300 }
301
302 EntityWrapperPtr SolveSpaceSolver_Builder::createFeature(
303     FeaturePtr theFeature,
304     const std::list<EntityWrapperPtr>& theAttributes,
305     const GroupID& theGroupID,
306     const EntityID& theSketchID) const
307 {
308   static EntityWrapperPtr aDummy;
309   if (!theFeature->data()->isValid())
310     return aDummy;
311
312   // Sketch
313   CompositeFeaturePtr aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
314   if (aSketch)
315     return createSketchEntity(aSketch, theGroupID);
316
317   // SketchPlugin features
318   std::shared_ptr<SketchPlugin_Feature> aFeature =
319       std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
320   if (!aFeature)
321     return aDummy;
322
323   // Verify the feature by its kind
324   const std::string& aFeatureKind = aFeature->getKind();
325   // Line
326   if (aFeatureKind == SketchPlugin_Line::ID())
327     return createLine(theFeature, theAttributes, theGroupID, theSketchID);
328   // Circle
329   else if (aFeatureKind == SketchPlugin_Circle::ID())
330     return createCircle(theFeature, theAttributes, theGroupID, theSketchID);
331   // Arc
332   else if (aFeatureKind == SketchPlugin_Arc::ID())
333     return createArc(theFeature, theAttributes, theGroupID, theSketchID);
334   // Point (it has low probability to be an attribute of constraint, so it is checked at the end)
335   else if (aFeatureKind == SketchPlugin_Point::ID() || 
336            aFeatureKind == SketchPlugin_IntersectionPoint::ID()) {
337     AttributePtr aPoint = theFeature->attribute(SketchPlugin_Point::COORD_ID());
338     if (!aPoint->isInitialized())
339       return aDummy;
340     EntityWrapperPtr aSub = theAttributes.empty() ? createAttribute(aPoint, theGroupID, theSketchID) :
341                             theAttributes.front();
342     if (!aSub)
343       return aDummy;
344
345     const Slvs_Entity& aSubEnt =
346         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(aSub)->entity();
347     EntityWrapperPtr aResult(new SolveSpaceSolver_EntityWrapper(theFeature, aPoint, aSubEnt));
348     aResult->setSubEntities(theAttributes);
349     return aResult;
350   }
351
352   // wrong entity
353   return aDummy;
354 }
355
356 EntityWrapperPtr SolveSpaceSolver_Builder::createAttribute(
357     AttributePtr theAttribute,
358     const GroupID& theGroupID,
359     const EntityID& theSketchID) const
360 {
361   AttributePtr anAttribute = theAttribute;
362   AttributeRefAttrPtr aRefAttr =
363       std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(anAttribute);
364   if (aRefAttr) {
365     if (aRefAttr->isObject()) {
366       // do not create features here
367       return EntityWrapperPtr();
368     } else
369       anAttribute = aRefAttr->attr();
370   }
371
372   std::list<ParameterWrapperPtr> aParameters;
373   Slvs_Entity anEntity;
374   anEntity.type = 0;
375
376   // Point in 3D
377   std::shared_ptr<GeomDataAPI_Point> aPoint =
378       std::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
379   if (aPoint) {
380     aParameters.push_back(createParameter(theGroupID, aPoint->x(), !aPoint->textX().empty()));
381     aParameters.push_back(createParameter(theGroupID, aPoint->y(), !aPoint->textY().empty()));
382     aParameters.push_back(createParameter(theGroupID, aPoint->z(), !aPoint->textZ().empty()));
383     // Create entity (parameters are not filled)
384     anEntity = Slvs_MakePoint3d(SLVS_E_UNKNOWN, (Slvs_hGroup)theGroupID,
385         SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
386   } else {
387     // Point in 2D
388     std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
389       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
390     if (aPoint2D) {
391       aParameters.push_back(createParameter(theGroupID, aPoint2D->x(), !aPoint2D->textX().empty()));
392       aParameters.push_back(createParameter(theGroupID, aPoint2D->y(), !aPoint2D->textY().empty()));
393       // Create entity (parameters are not filled)
394       anEntity = Slvs_MakePoint2d(SLVS_E_UNKNOWN, (Slvs_hGroup)theGroupID,
395           (Slvs_hEntity)theSketchID, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
396     } else {
397       // Scalar value (used for the distance entities)
398       AttributeDoublePtr aScalar =
399           std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
400       if (aScalar) {
401         aParameters.push_back(createParameter(theGroupID, aScalar->value(), !aScalar->text().empty()));
402         // Create entity (parameter is not filled)
403         anEntity = Slvs_MakeDistance(SLVS_E_UNKNOWN, (Slvs_hGroup)theGroupID,
404           (Slvs_hEntity)theSketchID, SLVS_E_UNKNOWN);
405       }
406     }
407   }
408
409   if (anEntity.type == 0) {
410     // unknown attribute type
411     return EntityWrapperPtr();
412   }
413
414   EntityWrapperPtr aResult(new SolveSpaceSolver_EntityWrapper(theAttribute, anEntity));
415   aResult->setParameters(aParameters);
416   return aResult;
417 }
418
419
420
421 EntityWrapperPtr SolveSpaceSolver_Builder::createSketchEntity(
422     CompositeFeaturePtr theSketch,
423     const GroupID& theGroupID) const
424 {
425   DataPtr aSketchData = theSketch->data();
426   if (!aSketchData || !aSketchData->isValid())
427     return EntityWrapperPtr(); // the sketch is incorrect
428
429   // Get parameters of workplane
430   AttributePtr aDirX    = aSketchData->attribute(SketchPlugin_Sketch::DIRX_ID());
431   AttributePtr aNorm    = aSketchData->attribute(SketchPlugin_Sketch::NORM_ID());
432   AttributePtr anOrigin = aSketchData->attribute(SketchPlugin_Sketch::ORIGIN_ID());
433   if (!anOrigin->isInitialized() || !aNorm->isInitialized() || !aDirX->isInitialized())
434     return EntityWrapperPtr();
435
436   EntityWrapperPtr aNewEnt;
437   std::list<EntityWrapperPtr> aSubs;
438
439   // Create SolveSpace entity corresponding to the sketch origin
440   aNewEnt = createAttribute(anOrigin, theGroupID);
441   if (!aNewEnt)
442     return EntityWrapperPtr();
443   aSubs.push_back(aNewEnt);
444
445   // Create SolveSpace entity corresponding the the sketch normal
446   aNewEnt = createNormal(aNorm, aDirX, theGroupID);
447   if (!aNewEnt)
448     return EntityWrapperPtr();
449   aSubs.push_back(aNewEnt);
450
451   // Create workplane
452   Slvs_Entity aWorkplane = Slvs_MakeWorkplane(SLVS_E_UNKNOWN, (Slvs_hGroup)theGroupID,
453       SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
454
455   aNewEnt = EntityWrapperPtr(
456       new SolveSpaceSolver_EntityWrapper(FeaturePtr(theSketch), aWorkplane));
457   aNewEnt->setSubEntities(aSubs);
458   return aNewEnt;
459 }
460
461 EntityWrapperPtr SolveSpaceSolver_Builder::createNormal(
462     AttributePtr theNormal,
463     AttributePtr theDirX,
464     const GroupID& theGroupID) const
465 {
466   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(theNormal);
467   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirX);
468   if (!aDirX || !aNorm ||
469       (fabs(aDirX->x()) + fabs(aDirX->y()) + fabs(aDirX->z()) < tolerance) || 
470       !aNorm->isInitialized())
471     return EntityWrapperPtr();
472   // calculate Y direction
473   std::shared_ptr<GeomAPI_Dir> aDirY(new GeomAPI_Dir(aNorm->dir()->cross(aDirX->dir())));
474
475   // quaternion parameters of normal vector
476   double qw, qx, qy, qz;
477   Slvs_MakeQuaternion(aDirX->x(), aDirX->y(), aDirX->z(), aDirY->x(), aDirY->y(), aDirY->z(), &qw,
478                       &qx, &qy, &qz);
479   double aNormCoord[4] = { qw, qx, qy, qz };
480
481   // Create parameters of the normal
482   std::list<ParameterWrapperPtr> aParameters;
483   for (int i = 0; i < 4; i++)
484     aParameters.push_back(createParameter(theGroupID, aNormCoord[i]));
485
486   // Create a normal with empty parameters
487   Slvs_Entity aNormalEnt = Slvs_MakeNormal3d(SLVS_E_UNKNOWN, (Slvs_hGroup)theGroupID,
488       SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
489   EntityWrapperPtr aNormal(new SolveSpaceSolver_EntityWrapper(theNormal, aNormalEnt));
490   aNormal->setParameters(aParameters);
491   return aNormal;
492 }
493
494 ParameterWrapperPtr SolveSpaceSolver_Builder::createParameter(
495     const GroupID& theGroup, const double theValue, const bool theExpr) const
496 {
497   Slvs_Param aParam = Slvs_MakeParam(SLVS_E_UNKNOWN, (Slvs_hGroup)theGroup, theValue);
498   ParameterWrapperPtr aWrapper(new SolveSpaceSolver_ParameterWrapper(aParam));
499   aWrapper->setIsParametric(theExpr);
500   return aWrapper;
501 }
502
503
504
505
506
507 // ================   Auxiliary functions   ==========================
508 EntityWrapperPtr createLine(FeaturePtr theFeature,
509                             const std::list<EntityWrapperPtr>& theAttributes,
510                             const GroupID& theGroupID,
511                             const EntityID& theSketchID)
512 {
513   EntityWrapperPtr aNewEntity;
514   std::list<EntityWrapperPtr> aSubs;
515
516   AttributePtr aStart = theFeature->attribute(SketchPlugin_Line::START_ID());
517   AttributePtr aEnd = theFeature->attribute(SketchPlugin_Line::END_ID());
518   if (!aStart->isInitialized() || !aEnd->isInitialized())
519     return aNewEntity;
520
521   EntityWrapperPtr aStartEnt, aEndEnt;
522   std::list<EntityWrapperPtr>::const_iterator anIt = theAttributes.begin();
523   for (; anIt != theAttributes.end(); ++anIt) {
524     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aSlvsEntity = 
525         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*anIt);
526     if (aSlvsEntity->isBase(aStart))
527       aStartEnt = aSlvsEntity;
528     else if (aSlvsEntity->isBase(aEnd))
529       aEndEnt = aSlvsEntity;
530   }
531   if (!aStartEnt || !aEndEnt)
532     return aNewEntity;
533
534   aSubs.push_back(aStartEnt);
535   aSubs.push_back(aEndEnt);
536   Slvs_Entity anEntity = Slvs_MakeLineSegment(SLVS_E_UNKNOWN, (Slvs_hGroup)theGroupID,
537       (Slvs_hEntity)theSketchID, (Slvs_hEntity)aStartEnt->id(), (Slvs_hEntity)aEndEnt->id());
538
539   aNewEntity = EntityWrapperPtr(new SolveSpaceSolver_EntityWrapper(theFeature, anEntity));
540   aNewEntity->setSubEntities(aSubs);
541   return aNewEntity;
542 }
543
544 EntityWrapperPtr createCircle(FeaturePtr theFeature,
545                               const std::list<EntityWrapperPtr>& theAttributes,
546                               const GroupID& theGroupID,
547                               const EntityID& theSketchID)
548 {
549   EntityWrapperPtr aNewEntity;
550   std::list<EntityWrapperPtr> aSubs;
551
552   AttributePtr aCenter = theFeature->attribute(SketchPlugin_Circle::CENTER_ID());
553   AttributePtr aRadius = theFeature->attribute(SketchPlugin_Circle::RADIUS_ID());
554   if (!aCenter->isInitialized() || !aRadius->isInitialized())
555     return aNewEntity;
556
557   EntityWrapperPtr aCenterEnt, aRadiusEnt, aNormalEnt;
558   std::list<EntityWrapperPtr>::const_iterator anIt = theAttributes.begin();
559   for (; anIt != theAttributes.end(); ++anIt) {
560     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aSlvsEntity = 
561         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*anIt);
562     if (aSlvsEntity->isBase(aCenter))
563       aCenterEnt = aSlvsEntity;
564     else if (aSlvsEntity->isBase(aRadius))
565       aRadiusEnt = aSlvsEntity;
566     else if (aSlvsEntity->type() == ENTITY_NORMAL)
567       aNormalEnt = aSlvsEntity;
568   }
569   if (!aCenterEnt || !aRadiusEnt || !aNormalEnt)
570     return aNewEntity;
571
572   aSubs.push_back(aCenterEnt);
573   aSubs.push_back(aRadiusEnt);
574   Slvs_Entity anEntity = Slvs_MakeCircle(SLVS_E_UNKNOWN, (Slvs_hGroup)theGroupID,
575       (Slvs_hEntity)theSketchID, (Slvs_hEntity)aCenterEnt->id(),
576       (Slvs_hEntity)aNormalEnt->id(), (Slvs_hEntity)aRadiusEnt->id());
577
578   aNewEntity = EntityWrapperPtr(new SolveSpaceSolver_EntityWrapper(theFeature, anEntity));
579   aNewEntity->setSubEntities(aSubs);
580   return aNewEntity;
581 }
582
583 EntityWrapperPtr createArc(FeaturePtr theFeature,
584                            const std::list<EntityWrapperPtr>& theAttributes,
585                            const GroupID& theGroupID,
586                            const EntityID& theSketchID)
587 {
588   EntityWrapperPtr aNewEntity;
589   std::list<EntityWrapperPtr> aSubs;
590
591   AttributePtr aCenter = theFeature->attribute(SketchPlugin_Arc::CENTER_ID());
592   AttributePtr aStart = theFeature->attribute(SketchPlugin_Arc::START_ID());
593   AttributePtr aEnd = theFeature->attribute(SketchPlugin_Arc::END_ID());
594   if (!aCenter->isInitialized() || !aStart->isInitialized() || !aEnd->isInitialized())
595     return aNewEntity;
596
597   EntityWrapperPtr aCenterEnt, aStartEnt, aEndEnt, aNormalEnt;
598   std::list<EntityWrapperPtr>::const_iterator anIt = theAttributes.begin();
599   for (; anIt != theAttributes.end(); ++anIt) {
600     std::shared_ptr<SolveSpaceSolver_EntityWrapper> aSlvsEntity = 
601         std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(*anIt);
602     if (aSlvsEntity->isBase(aCenter))
603       aCenterEnt = aSlvsEntity;
604     else if (aSlvsEntity->isBase(aStart))
605       aStartEnt = aSlvsEntity;
606     else if (aSlvsEntity->isBase(aEnd))
607       aEndEnt = aSlvsEntity;
608     else if (aSlvsEntity->type() == ENTITY_NORMAL)
609       aNormalEnt = aSlvsEntity;
610   }
611   if (!aCenterEnt || !aStartEnt || !aEndEnt || !aNormalEnt)
612     return aNewEntity;
613
614   aSubs.push_back(aCenterEnt);
615   aSubs.push_back(aStartEnt);
616   aSubs.push_back(aEndEnt);
617   Slvs_Entity anEntity = Slvs_MakeArcOfCircle(SLVS_E_UNKNOWN, (Slvs_hGroup)theGroupID,
618       (Slvs_hEntity)theSketchID, (Slvs_hEntity)aNormalEnt->id(),
619       (Slvs_hEntity)aCenterEnt->id(), (Slvs_hEntity)aStartEnt->id(), (Slvs_hEntity)aEndEnt->id());
620
621   aNewEntity = EntityWrapperPtr(new SolveSpaceSolver_EntityWrapper(theFeature, anEntity));
622   aNewEntity->setSubEntities(aSubs);
623   return aNewEntity;
624 }
625
626
627 void adjustTangency(ConstraintWrapperPtr theConstraint)
628 {
629   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
630
631   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
632     std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
633
634   // Collect start, end points of entities
635   std::shared_ptr<GeomAPI_Pnt2d> aStartEntPoints[2][2];
636   bool isCoinc[2][2] = {false};
637   const std::list<EntityWrapperPtr>& aSubs = aConstraint->entities();
638   std::list<EntityWrapperPtr>::const_iterator aSIt = aSubs.begin();
639   for (int i = 0; aSIt != aSubs.end(); ++aSIt, ++i) {
640     const std::list<EntityWrapperPtr>& aPoints = (*aSIt)->subEntities();
641     std::list<EntityWrapperPtr>::const_iterator aPIt = aPoints.begin();
642     if ((*aSIt)->type() == ENTITY_ARC)
643       ++aPIt;
644     for (int j = 0; aPIt != aPoints.end(); ++aPIt, ++j) {
645       aStartEntPoints[i][j] = aBuilder->point(*aPIt);
646       if (i > 0) { // check coincidence
647         for (int k = 0; k < 2; ++k)
648           if (aStartEntPoints[i][j]->distance(aStartEntPoints[0][k]) < tolerance)
649             isCoinc[0][k] = isCoinc[i][j] = true;
650       }
651     }
652   }
653
654   Slvs_Constraint& aSlvsConstraint = aConstraint->changeConstraint();
655   if (isCoinc[0][0] == false && isCoinc[0][1] == true)
656     aSlvsConstraint.other = 1;
657   else aSlvsConstraint.other = 0;
658   if (isCoinc[1][0] == false && isCoinc[1][1] == true)
659     aSlvsConstraint.other2 = 1;
660   else aSlvsConstraint.other2 = 0;
661 }
662
663 void adjustAngle(ConstraintWrapperPtr theConstraint)
664 {
665   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
666
667   std::shared_ptr<SolveSpaceSolver_ConstraintWrapper> aConstraint =
668     std::dynamic_pointer_cast<SolveSpaceSolver_ConstraintWrapper>(theConstraint);
669
670   bool isFixed[2][2];
671   std::shared_ptr<GeomAPI_Pnt2d> aPoints[2][2]; // start and end points of lines
672   const std::list<EntityWrapperPtr>& aConstrLines = aConstraint->entities();
673   std::list<EntityWrapperPtr>::const_iterator aCLIt = aConstrLines.begin();
674   for (int i = 0; aCLIt != aConstrLines.end(); ++i, ++aCLIt) {
675     const std::list<EntityWrapperPtr>& aLinePoints = (*aCLIt)->subEntities();
676     std::list<EntityWrapperPtr>::const_iterator aLPIt = aLinePoints.begin();
677     for (int j = 0; aLPIt != aLinePoints.end(); ++j, ++aLPIt) {
678       isFixed[i][j] = ((*aLPIt)->group() != theConstraint->group());
679       aPoints[i][j] = aBuilder->point(*aLPIt);
680     }
681   }
682
683   if (isFixed[0][0] && isFixed[0][1] && isFixed[1][0] && isFixed[1][1])
684     return; // both lines are fixed => no need to update them
685
686   std::shared_ptr<GeomAPI_Lin2d> aLine[2] = {
687     std::shared_ptr<GeomAPI_Lin2d>(new GeomAPI_Lin2d(aPoints[0][0], aPoints[0][1])),
688     std::shared_ptr<GeomAPI_Lin2d>(new GeomAPI_Lin2d(aPoints[1][0], aPoints[1][1]))
689   };
690   bool isReversed[2] = {
691     aConstraint->baseConstraint()->boolean(
692         SketchPlugin_ConstraintAngle::ANGLE_REVERSED_FIRST_LINE_ID())->value(),
693     aConstraint->baseConstraint()->boolean(
694         SketchPlugin_ConstraintAngle::ANGLE_REVERSED_SECOND_LINE_ID())->value()
695   };
696   std::shared_ptr<GeomAPI_Angle2d> anAngle(new GeomAPI_Angle2d(aLine[0], isReversed[0], aLine[1], isReversed[1]));
697   std::shared_ptr<GeomAPI_Pnt2d> aCenter = anAngle->center();
698
699   std::shared_ptr<GeomAPI_Dir2d> aDir[2];
700
701   Slvs_Constraint& aSlvsConstraint = aConstraint->changeConstraint();
702   aSlvsConstraint.other = false;
703   for (int i = 0; i < 2; i++) {
704     aDir[i] = aLine[i]->direction();
705     if (isReversed[i]) {
706       aSlvsConstraint.other = !aSlvsConstraint.other;
707       aDir[i]->reverse();
708     }
709   }
710
711   double aDist[2][2];
712   for (int i = 0; i < 2; i++) {
713     for (int j = 0; j < 2; j++) {
714       aDist[i][j] = aDir[i]->xy()->dot(aPoints[i][j]->xy()->decreased(aCenter->xy()));
715       if (fabs(aDist[i][j]) <= tolerance)
716         aDist[i][j] = 0.0;
717     }
718   }
719
720   // Recalculate positions of lines to avoid conflicting constraints
721   // while changing angle value several times
722   double cosA = cos(aConstraint->value() * PI / 180.0);
723   double sinA = sin(aConstraint->value() * PI / 180.0);
724   //if (aDir[0]->cross(aDir[1]) < 0.0)
725   //  sinA *= -1.0;
726   int aLineToUpd = 1;
727   if (isFixed[1][0] && isFixed[1][1]) {
728     sinA *= -1.0;
729     aLineToUpd = 0;
730   }
731   double x = aDir[1-aLineToUpd]->x() * cosA - aDir[1-aLineToUpd]->y() * sinA;
732   double y = aDir[1-aLineToUpd]->x() * sinA + aDir[1-aLineToUpd]->y() * cosA;
733
734   std::shared_ptr<GeomAPI_Pnt2d> aNewPoints[2];
735   for (int i = 0; i < 2; i++) {
736     aNewPoints[i] = std::shared_ptr<GeomAPI_Pnt2d>(
737         new GeomAPI_Pnt2d(aCenter->x() + x * aDist[aLineToUpd][i],
738                           aCenter->y() + y * aDist[aLineToUpd][i]));
739   }
740
741   std::shared_ptr<GeomAPI_XY> aDelta;
742   if (isFixed[aLineToUpd][0] && !isFixed[aLineToUpd][1])
743     aDelta = aPoints[aLineToUpd][0]->xy()->decreased(aNewPoints[0]->xy());
744   else if (!isFixed[aLineToUpd][0] && isFixed[aLineToUpd][1])
745     aDelta = aPoints[aLineToUpd][1]->xy()->decreased(aNewPoints[1]->xy());
746   if (aDelta) {
747     for (int i = 0; i < 2; i++) {
748       aNewPoints[i]->setX(aNewPoints[i]->x() + aDelta->x());
749       aNewPoints[i]->setY(aNewPoints[i]->y() + aDelta->y());
750     }
751   }
752
753   // Update positions of points
754   std::list<EntityWrapperPtr>::const_iterator anUpdLine = aConstrLines.begin();
755   if (aLineToUpd > 0) ++anUpdLine;
756   const std::list<EntityWrapperPtr>& anUpdPoints = (*anUpdLine)->subEntities();
757   std::list<EntityWrapperPtr>::const_iterator aPIt = anUpdPoints.begin();
758   for (int i = 0; aPIt != anUpdPoints.end(); ++aPIt, ++i) {
759     std::shared_ptr<GeomDataAPI_Point2D> aPnt2D =
760         std::dynamic_pointer_cast<GeomDataAPI_Point2D>((*aPIt)->baseAttribute());
761     aPnt2D->setValue(aNewPoints[i]);
762   }
763 }
764
765 void adjustMirror(ConstraintWrapperPtr theConstraint)
766 {
767   std::vector<EntityWrapperPtr> aPoints;
768   EntityWrapperPtr aMirrorLine;
769
770   const std::list<EntityWrapperPtr>& aSubs = theConstraint->entities();
771   std::list<EntityWrapperPtr>::const_iterator anIt = aSubs.begin();
772   for (; anIt != aSubs.end(); ++anIt) {
773     if ((*anIt)->type() == ENTITY_POINT)
774       aPoints.push_back(*anIt);
775     else if ((*anIt)->type() == ENTITY_LINE)
776       aMirrorLine = *anIt;
777   }
778
779   makeMirrorPoints(aPoints[0], aPoints[1], aMirrorLine);
780 }
781
782 void makeMirrorPoints(EntityWrapperPtr theOriginal,
783                       EntityWrapperPtr theMirrored,
784                       EntityWrapperPtr theMirrorLine)
785 {
786   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
787
788   std::shared_ptr<GeomAPI_Lin2d> aMirrorLine = aBuilder->line(theMirrorLine);
789   std::shared_ptr<GeomAPI_Dir2d> aMLDir = aMirrorLine->direction();
790   // orthogonal direction
791   aMLDir = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aMLDir->y(), -aMLDir->x()));
792
793   std::shared_ptr<GeomAPI_Pnt2d> aPoint = aBuilder->point(theOriginal);
794   std::shared_ptr<GeomAPI_XY> aVec = aPoint->xy()->decreased(aMirrorLine->location()->xy());
795   double aDist = aVec->dot(aMLDir->xy());
796   aVec = aPoint->xy()->added(aMLDir->xy()->multiplied(-2.0 * aDist));
797   double aCoord[2] = {aVec->x(), aVec->y()};
798   std::list<ParameterWrapperPtr>::const_iterator aMIt = theMirrored->parameters().begin();
799   for (int i = 0; aMIt != theMirrored->parameters().end(); ++aMIt, ++i)
800     (*aMIt)->setValue(aCoord[i]);
801
802   // update corresponding attribute
803   AttributePtr anAttr = std::dynamic_pointer_cast<SolveSpaceSolver_EntityWrapper>(theMirrored)->baseAttribute();
804   if (anAttr) {
805     std::shared_ptr<GeomDataAPI_Point2D> aMirroredPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr);
806     aMirroredPnt->setValue(aCoord[0], aCoord[1]);
807   }
808 }
809
810 void adjustPtLineDistance(ConstraintWrapperPtr theConstraint)
811 {
812   BuilderPtr aBuilder = SolveSpaceSolver_Builder::getInstance();
813
814   std::shared_ptr<GeomAPI_Pnt2d> aPoint;
815   std::shared_ptr<GeomAPI_Lin2d> aLine;
816   std::list<EntityWrapperPtr> aSubs = theConstraint->entities();
817   std::list<EntityWrapperPtr>::const_iterator aSIt = aSubs.begin();
818   for (; aSIt != aSubs.end(); ++aSIt) {
819     if ((*aSIt)->type() == ENTITY_POINT)
820       aPoint = aBuilder->point(*aSIt);
821     else if ((*aSIt)->type() == ENTITY_LINE)
822       aLine = aBuilder->line(*aSIt);
823   }
824
825   std::shared_ptr<GeomAPI_XY> aLineVec = aLine->direction()->xy();
826   std::shared_ptr<GeomAPI_XY> aPtLineVec = aPoint->xy()->decreased(aLine->location()->xy());
827   if (aPtLineVec->cross(aLineVec) * theConstraint->value() < 0.0)
828     theConstraint->setValue(theConstraint->value() * (-1.0));
829 }