Salome HOME
Merge remote-tracking branch 'remotes/origin/SolveSpace'
[modules/shaper.git] / src / SketchSolver / SketchSolver_ConstraintManager.cpp
1 // File:    SketchSolver_ConstraintManager.cpp
2 // Created: 08 May 2014
3 // Author:  Artem ZHIDKOV
4
5 #include "SketchSolver_ConstraintManager.h"
6
7 #include <Events_Loop.h>
8 #include <ModelAPI_AttributeDouble.h>
9 #include <ModelAPI_AttributeRefList.h>
10 #include <ModelAPI_Data.h>
11 #include <Model_Events.h>
12
13 #include <SketchPlugin_Constraint.h>
14
15 #include <SketchPlugin_Arc.h>
16 #include <SketchPlugin_Circle.h>
17 #include <SketchPlugin_Line.h>
18 #include <SketchPlugin_Point.h>
19 #include <SketchPlugin_Sketch.h>
20
21
22 // Initialization of constraint manager self pointer
23 SketchSolver_ConstraintManager* SketchSolver_ConstraintManager::_self = 0;
24
25 /// Global constraint manager object
26 SketchSolver_ConstraintManager* myManager = SketchSolver_ConstraintManager::Instance();
27
28
29 // ========================================================
30 // ========= SketchSolver_ConstraintManager ===============
31 // ========================================================
32 SketchSolver_ConstraintManager* SketchSolver_ConstraintManager::Instance()
33 {
34   if (!_self)
35     _self = new SketchSolver_ConstraintManager();
36   return _self;
37 }
38
39 SketchSolver_ConstraintManager::SketchSolver_ConstraintManager()
40 {
41   myGroups.clear();
42
43   // Register in event loop
44   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_FEATURE_CREATED));
45   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_FEATURE_UPDATED));
46   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_FEATURE_DELETED));
47   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_FEATURE_MOVED));
48 }
49
50 SketchSolver_ConstraintManager::~SketchSolver_ConstraintManager()
51 {
52   myGroups.clear();
53 }
54
55 // ============================================================================
56 //  Function: processEvent
57 //  Class:    SketchSolver_PluginManager
58 //  Purpose:  listen the event loop and process the message
59 // ============================================================================
60 void SketchSolver_ConstraintManager::processEvent(const Events_Message* theMessage)
61 {
62   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_FEATURE_CREATED) ||
63       theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_FEATURE_UPDATED) || 
64       theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_FEATURE_MOVED))
65   {
66     const Model_FeatureUpdatedMessage* anUpdateMsg = dynamic_cast<const Model_FeatureUpdatedMessage*>(theMessage);
67     std::set< boost::shared_ptr<ModelAPI_Feature> > aFeatures = anUpdateMsg->features();
68
69     bool isModifiedEvt = theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_FEATURE_MOVED);
70     if (!isModifiedEvt)
71     {
72       std::set< boost::shared_ptr<ModelAPI_Feature> >::iterator aFeatIter;
73       for (aFeatIter = aFeatures.begin(); aFeatIter != aFeatures.end(); aFeatIter++)
74       {
75         // Only sketches and constraints can be added by Create event
76         const std::string& aFeatureKind = (*aFeatIter)->getKind();
77         if (aFeatureKind.compare("Sketch") == 0)
78         {
79           boost::shared_ptr<SketchPlugin_Feature> aSketch =
80             boost::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
81           if (aSketch)
82             changeWorkplane(aSketch);
83           continue;
84         }
85         boost::shared_ptr<SketchPlugin_Constraint> aConstraint =
86           boost::dynamic_pointer_cast<SketchPlugin_Constraint>(*aFeatIter);
87         if (aConstraint)
88           changeConstraint(aConstraint);
89         else
90         {
91           // Sketch plugin features can be only updated
92           boost::shared_ptr<SketchPlugin_Feature> aFeature =
93             boost::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
94           if (aFeature)
95             updateEntity(aFeature);
96         }
97       }
98     }
99
100     // Solve the set of constraints
101     resolveConstraints();
102   }
103   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_FEATURE_DELETED))
104   {
105     const Model_FeatureDeletedMessage* aDeleteMsg = dynamic_cast<const Model_FeatureDeletedMessage*>(theMessage);
106     const std::set<std::string>& aFeatureGroups = aDeleteMsg->groups();
107
108     // Find "Sketch" in groups. The constraint groups should be updated when an object removed from Sketch
109     std::set<std::string>::const_iterator aFGrIter;
110     for (aFGrIter = aFeatureGroups.begin(); aFGrIter != aFeatureGroups.end(); aFGrIter++)
111       if (aFGrIter->compare("Sketch") == 0)
112         break;
113     
114     if (aFGrIter != aFeatureGroups.end())
115     {
116       std::vector<SketchSolver_ConstraintGroup*>::iterator aGroupIter = myGroups.begin();
117       while (aGroupIter != myGroups.end())
118       {
119         if ((*aGroupIter)->updateGroup())
120         { // the group should be removed
121           delete *aGroupIter;
122           int aShift = aGroupIter - myGroups.begin();
123           myGroups.erase(aGroupIter);
124           aGroupIter = myGroups.begin() + aShift;
125         }
126         else aGroupIter++;
127       }
128     }
129   }
130 }
131
132 // ============================================================================
133 //  Function: changeWorkplane
134 //  Class:    SketchSolver_PluginManager
135 //  Purpose:  update workplane by given parameters of the sketch
136 // ============================================================================
137 bool SketchSolver_ConstraintManager::changeWorkplane(boost::shared_ptr<SketchPlugin_Feature> theSketch)
138 {
139   bool aResult = true; // changed when a workplane wrongly updated
140   bool isUpdated = false;
141   // Try to update specified workplane in all groups
142   std::vector<SketchSolver_ConstraintGroup*>::iterator aGroupIter;
143   for (aGroupIter = myGroups.begin(); aGroupIter != myGroups.end(); aGroupIter++)
144     if ((*aGroupIter)->isBaseWorkplane(theSketch))
145     {
146       isUpdated = true;
147       if (!(*aGroupIter)->updateWorkplane())
148         aResult = false;
149     }
150   // If the workplane is not updated, so this is a new workplane
151   if (!isUpdated)
152   {
153     SketchSolver_ConstraintGroup* aNewGroup = new SketchSolver_ConstraintGroup(theSketch);
154     // Verify that the group is created successfully
155     if (!aNewGroup->isBaseWorkplane(theSketch))
156     {
157       delete aNewGroup;
158       return false;
159     }
160     myGroups.push_back(aNewGroup);
161   }
162   return aResult;
163 }
164
165 // ============================================================================
166 //  Function: changeConstraint
167 //  Class:    SketchSolver_PluginManager
168 //  Purpose:  create/update the constraint and place it into appropriate group
169 // ============================================================================
170 bool SketchSolver_ConstraintManager::changeConstraint(
171               boost::shared_ptr<SketchPlugin_Constraint> theConstraint)
172 {
173   // Search the groups which this constraint touches
174   std::set<Slvs_hGroup> aGroups;
175   findGroups(theConstraint, aGroups);
176
177   // Process the groups list
178   if (aGroups.size() == 0)
179   { // There are no groups applicable for this constraint => create new one
180     boost::shared_ptr<SketchPlugin_Feature> aWP = findWorkplaneForConstraint(theConstraint);
181     if (!aWP) return false;
182     SketchSolver_ConstraintGroup* aGroup = new SketchSolver_ConstraintGroup(aWP);
183     if (!aGroup->changeConstraint(theConstraint))
184     {
185       delete aGroup;
186       return false;
187     }
188     myGroups.push_back(aGroup);
189     return true;
190   }
191   else if (aGroups.size() == 1)
192   { // Only one group => add constraint into it
193     Slvs_hGroup aGroupId = *(aGroups.begin());
194     std::vector<SketchSolver_ConstraintGroup*>::iterator aGroupIter;
195     for (aGroupIter = myGroups.begin(); aGroupIter != myGroups.end(); aGroupIter++)
196       if ((*aGroupIter)->getId() == aGroupId)
197         return (*aGroupIter)->changeConstraint(theConstraint);
198   }
199   else if (aGroups.size() > 1)
200   { // Several groups applicable for this constraint => need to merge them
201     std::set<Slvs_hGroup>::const_iterator aGroupsIter = aGroups.begin();
202
203     // Search first group
204     std::vector<SketchSolver_ConstraintGroup*>::iterator aFirstGroupIter;
205     for (aFirstGroupIter = myGroups.begin(); aFirstGroupIter != myGroups.end(); aFirstGroupIter++)
206       if ((*aFirstGroupIter)->getId() == *aGroupsIter)
207         break;
208     if (aFirstGroupIter == myGroups.end())
209       return false;
210
211     // Append other groups to the first one
212     std::vector<SketchSolver_ConstraintGroup*>::iterator anOtherGroupIter = aFirstGroupIter + 1;
213     for (aGroupsIter++; aGroupsIter != aGroups.end(); aGroupsIter++)
214     {
215       for ( ; anOtherGroupIter != myGroups.end(); anOtherGroupIter++)
216         if ((*anOtherGroupIter)->getId() == *aGroupsIter)
217           break;
218       if (anOtherGroupIter == myGroups.end())
219       { // Group disappears
220         anOtherGroupIter = aFirstGroupIter + 1;
221         continue;
222       }
223
224       (*aFirstGroupIter)->mergeGroups(**anOtherGroupIter);
225       int aShiftFirst = aFirstGroupIter - myGroups.begin();
226       int aShiftOther = anOtherGroupIter - myGroups.begin();
227       delete *anOtherGroupIter;
228       myGroups.erase(anOtherGroupIter);
229       aFirstGroupIter  = myGroups.begin() + aShiftFirst;
230       anOtherGroupIter = myGroups.begin() + aShiftOther;
231     }
232
233     return (*aFirstGroupIter)->changeConstraint(theConstraint);
234   }
235
236   // Something goes wrong
237   return false;
238 }
239
240 // ============================================================================
241 //  Function: updateEntity
242 //  Class:    SketchSolver_PluginManager
243 //  Purpose:  update any element on the sketch, which is used by constraints
244 // ============================================================================
245 void SketchSolver_ConstraintManager::updateEntity(boost::shared_ptr<SketchPlugin_Feature> theFeature)
246 {
247   // Create list of attributes depending on type of the feature
248   std::vector<std::string> anAttrList;
249   const std::string& aFeatureKind = theFeature->getKind();
250   // Point
251   if (aFeatureKind.compare("SketchPoint") == 0)
252     anAttrList.push_back(POINT_ATTR_COORD);
253   // Line
254   else if (aFeatureKind.compare("SketchLine") == 0)
255   {
256     anAttrList.push_back(LINE_ATTR_START);
257     anAttrList.push_back(LINE_ATTR_END);
258   }
259   // Circle
260   else if (aFeatureKind.compare("SketchCircle") == 0)
261   {
262     anAttrList.push_back(CIRCLE_ATTR_CENTER);
263     anAttrList.push_back(CIRCLE_ATTR_RADIUS);
264   }
265   // Arc
266   else if (aFeatureKind.compare("SketchArc") == 0)
267   {
268     anAttrList.push_back(ARC_ATTR_CENTER);
269     anAttrList.push_back(ARC_ATTR_START);
270     anAttrList.push_back(ARC_ATTR_END);
271   }
272   /// \todo Other types of features should be implemented
273
274   // Check changing of feature's attributes (go through the groups and search usage of the attributes)
275   std::vector<std::string>::const_iterator anAttrIter;
276   for (anAttrIter = anAttrList.begin(); anAttrIter != anAttrList.end(); anAttrIter++)
277   {
278     std::vector<SketchSolver_ConstraintGroup*>::iterator aGroupIter;
279     for (aGroupIter = myGroups.begin(); aGroupIter != myGroups.end(); aGroupIter++)
280     {
281       boost::shared_ptr<ModelAPI_Attribute> anAttribute =
282         boost::dynamic_pointer_cast<ModelAPI_Attribute>(theFeature->data()->attribute(*anAttrIter));
283       (*aGroupIter)->updateEntityIfPossible(anAttribute);
284     }
285   }
286 }
287
288
289 // ============================================================================
290 //  Function: findGroups
291 //  Class:    SketchSolver_PluginManager
292 //  Purpose:  search groups of entities interacting with given constraint
293 // ============================================================================
294 void SketchSolver_ConstraintManager::findGroups(
295               boost::shared_ptr<SketchPlugin_Constraint> theConstraint,
296               std::set<Slvs_hGroup>&                     theGroupIDs) const
297 {
298   boost::shared_ptr<SketchPlugin_Feature> aWP = findWorkplaneForConstraint(theConstraint);
299
300   SketchSolver_ConstraintGroup* anEmptyGroup = 0; // appropriate empty group for specified constraint
301   std::vector<SketchSolver_ConstraintGroup*>::const_iterator aGroupIter;
302   for (aGroupIter = myGroups.begin(); aGroupIter != myGroups.end(); aGroupIter++)
303     if (aWP == (*aGroupIter)->getWorkplane() && (*aGroupIter)->isInteract(theConstraint))
304     {
305       if (!(*aGroupIter)->isEmpty())
306         theGroupIDs.insert((*aGroupIter)->getId());
307       else if (!anEmptyGroup)
308         anEmptyGroup = *aGroupIter;
309     }
310
311   // When only empty group is found, use it
312   if (anEmptyGroup && theGroupIDs.empty())
313     theGroupIDs.insert(anEmptyGroup->getId());
314 }
315
316 // ============================================================================
317 //  Function: findWorkplaneForConstraint
318 //  Class:    SketchSolver_PluginManager
319 //  Purpose:  search workplane containing given constraint
320 // ============================================================================
321 boost::shared_ptr<SketchPlugin_Feature> SketchSolver_ConstraintManager::findWorkplaneForConstraint(
322               boost::shared_ptr<SketchPlugin_Constraint> theConstraint) const
323 {
324   // Already verified workplanes
325   std::set< boost::shared_ptr<SketchPlugin_Feature> > aVerified;
326
327   std::vector<SketchSolver_ConstraintGroup*>::const_iterator aGroupIter;
328   for (aGroupIter = myGroups.begin(); aGroupIter != myGroups.end(); aGroupIter++)
329   {
330     boost::shared_ptr<SketchPlugin_Feature> aWP = (*aGroupIter)->getWorkplane();
331     if (aVerified.find(aWP) != aVerified.end())
332       continue;
333
334     boost::shared_ptr<ModelAPI_AttributeRefList> aWPFeatures =
335       boost::dynamic_pointer_cast<ModelAPI_AttributeRefList>(aWP->data()->attribute(SKETCH_ATTR_FEATURES));
336     std::list< boost::shared_ptr<ModelAPI_Feature> > aFeaturesList = aWPFeatures->list();
337     std::list< boost::shared_ptr<ModelAPI_Feature> >::const_iterator anIter;
338     for (anIter = aFeaturesList.begin(); anIter != aFeaturesList.end(); anIter++)
339       if (*anIter == theConstraint)
340         return aWP; // workplane is found
341     aVerified.insert(aWP);
342   }
343
344   return boost::shared_ptr<SketchPlugin_Feature>();
345 }
346
347 // ============================================================================
348 //  Function: resolveConstraints
349 //  Class:    SketchSolver_PluginManager
350 //  Purpose:  change entities according to available constraints
351 // ============================================================================
352 void SketchSolver_ConstraintManager::resolveConstraints()
353 {
354   std::vector<SketchSolver_ConstraintGroup*>::iterator aGroupIter;
355   for (aGroupIter = myGroups.begin(); aGroupIter != myGroups.end(); aGroupIter++)
356     (*aGroupIter)->resolveConstraints();
357
358   // Features may be updated => send events
359   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_UPDATED));
360 }
361