Salome HOME
ce740539aea0d73a127bded41ccf41f9a7bf7535
[modules/shaper.git] / src / SketchSolver / SketchSolver_Group.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SketchSolver_Group.cpp
4 // Created: 27 May 2014
5 // Author:  Artem ZHIDKOV
6
7 #include "SketchSolver_Group.h"
8 #include <SketchSolver_Error.h>
9 #include <SketchSolver_Manager.h>
10
11 #include <PlaneGCSSolver_Solver.h>
12 #include <PlaneGCSSolver_Storage.h>
13 #include <PlaneGCSSolver_Tools.h>
14
15 #include <Events_InfoMessage.h>
16 #include <ModelAPI_AttributeString.h>
17 #include <ModelAPI_Events.h>
18 #include <SketchPlugin_ConstraintMirror.h>
19 #include <SketchPlugin_ConstraintRigid.h>
20 #include <SketchPlugin_MultiRotation.h>
21 #include <SketchPlugin_MultiTranslation.h>
22
23
24 static void sendMessage(const char* theMessageName)
25 {
26   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
27       new Events_Message(Events_Loop::eventByName(theMessageName)));
28   Events_Loop::loop()->send(aMessage);
29 }
30
31 static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& theConflicting)
32 {
33   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
34       std::shared_ptr<ModelAPI_SolverFailedMessage>(
35       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
36   aMessage->setObjects(theConflicting);
37   Events_Loop::loop()->send(aMessage);
38 }
39
40 static void sendMessage(const char* theMessageName,
41                         const CompositeFeaturePtr& theSketch,
42                         const int theDOF)
43 {
44   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
45       std::shared_ptr<ModelAPI_SolverFailedMessage>(
46       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
47
48   std::set<ObjectPtr> anObjects;
49   anObjects.insert(theSketch);
50   aMessage->setObjects(anObjects);
51   aMessage->dof(theDOF);
52
53   Events_Loop::loop()->send(aMessage);
54 }
55
56
57
58 // ========================================================
59 // =========  SketchSolver_Group  ===============
60 // ========================================================
61
62 SketchSolver_Group::SketchSolver_Group(const CompositeFeaturePtr& theWorkplane)
63   : mySketch(theWorkplane),
64     myPrevResult(PlaneGCSSolver_Solver::STATUS_UNKNOWN),
65     myDOF(0),
66     myIsEventsBlocked(false),
67     myMultiConstraintUpdateStack(0)
68 {
69   mySketchSolver = SolverPtr(new PlaneGCSSolver_Solver);
70   myStorage = StoragePtr(new PlaneGCSSolver_Storage(mySketchSolver));
71 }
72
73 SketchSolver_Group::~SketchSolver_Group()
74 {
75   myConstraints.clear();
76   // send the message that there is no more conflicting constraints
77   if (!myConflictingConstraints.empty()) {
78     sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
79     myConflictingConstraints.clear();
80   }
81 }
82
83 // ============================================================================
84 //  Function: changeConstraint
85 //  Class:    SketchSolver_Group
86 //  Purpose:  create/update the constraint in the group
87 // ============================================================================
88 bool SketchSolver_Group::changeConstraint(
89     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
90 {
91   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
92   if (isNewConstraint) {
93     // Add constraint to the current group
94     SolverConstraintPtr aConstraint = PlaneGCSSolver_Tools::createConstraint(theConstraint);
95     if (!aConstraint)
96       return false;
97     aConstraint->process(myStorage, myIsEventsBlocked);
98     if (!aConstraint->error().empty()) {
99       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
100         return false; // some attribute are not initialized yet, don't show message
101       Events_InfoMessage("SketchSolver_Group", aConstraint->error(), this).send();
102     }
103     myConstraints[theConstraint] = aConstraint;
104   }
105   else
106     myConstraints[theConstraint]->update();
107
108   // constraint is created/updated => reset stack of "multi" constraints updates
109   myMultiConstraintUpdateStack = 0;
110   return true;
111 }
112
113 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
114 {
115   return myStorage->update(theFeature);
116 }
117
118 bool SketchSolver_Group::moveFeature(FeaturePtr theFeature)
119 {
120   bool isFeatureExists = (myStorage->entity(theFeature).get() != 0);
121   if (myDOF == 0 && isFeatureExists) {
122     // avoid moving elements of fully constrained sketch
123     myStorage->refresh();
124     return true;
125   }
126
127   // Create temporary Fixed constraint
128   std::shared_ptr<SketchSolver_ConstraintFixed> aConstraint =
129       PlaneGCSSolver_Tools::createMovementConstraint(theFeature);
130   if (!aConstraint)
131     return false;
132   SolverConstraintPtr(aConstraint)->process(myStorage, myIsEventsBlocked);
133   if (aConstraint->error().empty()) {
134     setTemporary(aConstraint);
135     if (!myStorage->isEmpty())
136       myStorage->setNeedToResolve(true);
137
138     mySketchSolver->initialize();
139     aConstraint->moveFeature();
140   }
141
142   // notify all observers that theFeature has been changed
143   myStorage->notify(theFeature);
144   return true;
145 }
146
147 // ============================================================================
148 //  Function: resolveConstraints
149 //  Class:    SketchSolver_Group
150 //  Purpose:  solve the set of constraints for the current group
151 // ============================================================================
152 bool SketchSolver_Group::resolveConstraints()
153 {
154   static const int MAX_STACK_SIZE = 5;
155   // check the "Multi" constraints do not drop sketch into infinite loop
156   if (myMultiConstraintUpdateStack > MAX_STACK_SIZE) {
157     myMultiConstraintUpdateStack = 0;
158     myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
159     // generate error message due to loop update of the sketch
160     getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
161       ->setValue(SketchSolver_Error::INFINITE_LOOP());
162     sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
163     return false;
164   }
165
166   bool aResolved = false;
167   bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
168   if (myStorage->isNeedToResolve() &&
169       (!isGroupEmpty || !myConflictingConstraints.empty() ||
170         myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED)) {
171
172     PlaneGCSSolver_Solver::SolveStatus aResult = PlaneGCSSolver_Solver::STATUS_OK;
173     try {
174       if (!isGroupEmpty)
175         aResult = mySketchSolver->solve();
176       if (aResult == PlaneGCSSolver_Solver::STATUS_FAILED &&
177           !myTempConstraints.empty()) {
178         mySketchSolver->undo();
179         removeTemporaryConstraints();
180         aResult = mySketchSolver->solve();
181       }
182     } catch (...) {
183       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
184         ->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
185       if (myPrevResult == PlaneGCSSolver_Solver::STATUS_OK ||
186           myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
187         // the error message should be changed before sending the message
188         sendMessage(EVENT_SOLVER_FAILED);
189         myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
190       }
191       mySketchSolver->undo();
192       return false;
193     }
194     // solution succeeded, store results into correspondent attributes
195     if (aResult == PlaneGCSSolver_Solver::STATUS_OK ||
196         aResult == PlaneGCSSolver_Solver::STATUS_EMPTYSET) {
197       myStorage->setNeedToResolve(false);
198       myStorage->refresh();
199
200       // additional check that copied entities used in Mirror and other "Multi" constraints
201       // is not connected with their originals by constraints.
202       myMultiConstraintUpdateStack += 1;
203       aResolved = true;
204       if (myStorage->isNeedToResolve())
205         aResolved = resolveConstraints();
206
207       if (aResolved) {
208         myMultiConstraintUpdateStack -= 1;
209
210         if (myPrevResult != PlaneGCSSolver_Solver::STATUS_OK ||
211             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
212           getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
213           std::set<ObjectPtr> aConflicting = myConflictingConstraints;
214           myConflictingConstraints.clear();
215           myPrevResult = PlaneGCSSolver_Solver::STATUS_OK;
216           // the error message should be changed before sending the message
217           sendMessage(EVENT_SOLVER_REPAIRED, aConflicting);
218         }
219       }
220
221       // show degrees of freedom
222       computeDoF();
223     } else {
224       mySketchSolver->undo();
225       if (!myConstraints.empty()) {
226         // the error message should be changed before sending the message
227         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
228           ->setValue(SketchSolver_Error::CONSTRAINTS());
229         if (myPrevResult != aResult ||
230             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN ||
231             myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED) {
232           // Obtain list of conflicting constraints
233           std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
234
235           if (!myConflictingConstraints.empty()) {
236             std::set<ObjectPtr>::iterator anIt = aConflicting.begin();
237             for (; anIt != aConflicting.end(); ++anIt)
238               myConflictingConstraints.erase(*anIt);
239             if (!myConflictingConstraints.empty()) {
240               // some constraints does not conflict, send corresponding message
241               sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
242             }
243           }
244           myConflictingConstraints = aConflicting;
245           if (!myConflictingConstraints.empty())
246             sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
247           myPrevResult = aResult;
248         }
249       }
250     }
251
252   } else if (isGroupEmpty && isWorkplaneValid())
253     computeDoF();
254   removeTemporaryConstraints();
255   myStorage->setNeedToResolve(false);
256   return aResolved;
257 }
258
259 // ============================================================================
260 //  Function: computeDoF
261 //  Class:    SketchSolver_Group
262 //  Purpose:  compute DoF of the sketch and set corresponding field
263 // ============================================================================
264 void SketchSolver_Group::computeDoF()
265 {
266   std::ostringstream aDoFMsg;
267   int aDoF = mySketchSolver->dof();
268   /// "DoF = 0" content of string value is used in PartSet by Sketch edit
269   /// If it is changed, it should be corrected also there
270   if (aDoF == 0)
271     aDoFMsg << "Sketch is fully fixed (DoF = 0)";
272   else
273     aDoFMsg << "DoF (degrees of freedom) = " << aDoF;
274   mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aDoFMsg.str());
275
276   if (aDoF > 0 && myDOF == 0)
277     sendMessage(EVENT_SKETCH_UNDER_CONSTRAINED, mySketch, aDoF);
278   else if (aDoF == 0 && myDOF > 0)
279     sendMessage(EVENT_SKETCH_FULLY_CONSTRAINED, mySketch, aDoF);
280   else if (aDoF < 0)
281     sendMessage(EVENT_SKETCH_OVER_CONSTRAINED, mySketch, aDoF);
282
283   myDOF = aDoF;
284 }
285
286 // ============================================================================
287 //  Function: repairConsistency
288 //  Class:    SketchSolver_Group
289 //  Purpose:  search removed entities and constraints
290 // ============================================================================
291 void SketchSolver_Group::repairConsistency()
292 {
293   if (!areConstraintsValid() || !myStorage->areFeaturesValid()) {
294     // remove invalid constraints
295     std::set<ConstraintPtr> anInvalidConstraints;
296     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
297     for (; aCIter != myConstraints.end(); ++aCIter) {
298       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
299         anInvalidConstraints.insert(aCIter->first);
300     }
301     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
302     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
303       removeConstraint(*aRemoveIt);
304
305     // remove invalid features
306     myStorage->removeInvalidEntities();
307
308     // show DoF
309     computeDoF();
310   }
311 }
312
313 // ============================================================================
314 //  Function: removeTemporaryConstraints
315 //  Class:    SketchSolver_Group
316 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
317 //            resolving the set of constraints
318 // ============================================================================
319 void SketchSolver_Group::removeTemporaryConstraints()
320 {
321   if (!myTempConstraints.empty()) {
322     mySketchSolver->removeConstraint(CID_MOVEMENT);
323
324     std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
325     for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
326       (*aTmpIt)->remove();
327
328     myTempConstraints.clear();
329   }
330
331   myStorage->setNeedToResolve(false);
332 }
333
334 // ============================================================================
335 //  Function: removeConstraint
336 //  Class:    SketchSolver_Group
337 //  Purpose:  remove constraint and all unused entities
338 // ============================================================================
339 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
340 {
341   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
342   for (; aCIter != myConstraints.end(); aCIter++)
343     if (aCIter->first == theConstraint) {
344       aCIter->second->remove(); // the constraint is not fully removed
345
346       // constraint is removed => reset stack of "multi" constraints updates
347       myMultiConstraintUpdateStack = 0;
348       break;
349     }
350   if (aCIter != myConstraints.end())
351     myConstraints.erase(aCIter);
352 }
353
354 // ============================================================================
355 //  Function: setTemporary
356 //  Class:    SketchSolver_Group
357 //  Purpose:  append given constraint to the group of temporary constraints
358 // ============================================================================
359 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
360 {
361   myTempConstraints.insert(theConstraint);
362 }
363
364 // ============================================================================
365 //  Function: blockEvents
366 //  Class:    SketchSolver_Group
367 //  Purpose:  block or unblock events from features in this group
368 // ============================================================================
369 void SketchSolver_Group::blockEvents(bool isBlocked)
370 {
371   if (myIsEventsBlocked == isBlocked)
372     return;
373
374   // block/unblock events from the features in the storage
375   myStorage->blockEvents(isBlocked);
376
377   // block/unblock events from constraints
378   ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
379   for (; aCIt != myConstraints.end(); ++aCIt)
380     aCIt->second->blockEvents(isBlocked);
381
382   myIsEventsBlocked = isBlocked;
383 }
384
385 bool SketchSolver_Group::areConstraintsValid() const
386 {
387   // Check the constraints are valid
388   ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
389   for (; aCIter != myConstraints.end(); ++aCIter)
390     if (!aCIter->first->data() || !aCIter->first->data()->isValid())
391       return false;
392   return true;
393 }