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