Salome HOME
Task 2.5 Show where the remaining degrees of freedom are (issue #2997)
[modules/shaper.git] / src / SketchSolver / SketchSolver_Group.cpp
1 // Copyright (C) 2014-2019  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include "SketchSolver_Group.h"
21 #include <SketchSolver_Error.h>
22 #include <SketchSolver_Manager.h>
23
24 #include <PlaneGCSSolver_Solver.h>
25 #include <PlaneGCSSolver_Storage.h>
26 #include <PlaneGCSSolver_Tools.h>
27
28 #include <Events_InfoMessage.h>
29 #include <ModelAPI_AttributeString.h>
30 #include <ModelAPI_Events.h>
31 #include <SketchPlugin_ConstraintMirror.h>
32 #include <SketchPlugin_ConstraintRigid.h>
33 #include <SketchPlugin_MultiRotation.h>
34 #include <SketchPlugin_MultiTranslation.h>
35
36 #include <Config_Translator.h>
37
38
39 static void sendMessage(const char* theMessageName)
40 {
41   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
42       new Events_Message(Events_Loop::eventByName(theMessageName)));
43   Events_Loop::loop()->send(aMessage);
44 }
45
46 static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& theConflicting)
47 {
48   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
49       std::shared_ptr<ModelAPI_SolverFailedMessage>(
50       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
51   aMessage->setObjects(theConflicting);
52   Events_Loop::loop()->send(aMessage);
53 }
54
55 static void sendMessage(const char* theMessageName,
56                         const CompositeFeaturePtr& theSketch,
57                         const int theDOF)
58 {
59   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
60       std::shared_ptr<ModelAPI_SolverFailedMessage>(
61       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
62
63   std::set<ObjectPtr> anObjects;
64   anObjects.insert(theSketch);
65   aMessage->setObjects(anObjects);
66   aMessage->dof(theDOF);
67
68   Events_Loop::loop()->send(aMessage);
69 }
70
71
72
73 // ========================================================
74 // =========       SketchSolver_Group       ===============
75 // ========================================================
76
77 SketchSolver_Group::SketchSolver_Group(const CompositeFeaturePtr& theWorkplane)
78   : myPrevResult(PlaneGCSSolver_Solver::STATUS_UNKNOWN),
79     myDOF(-1),
80     myIsEventsBlocked(false),
81     myMultiConstraintUpdateStack(0)
82 {
83   mySketchSolver = SolverPtr(new PlaneGCSSolver_Solver);
84   myStorage = StoragePtr(new PlaneGCSSolver_Storage(mySketchSolver));
85   updateSketch(theWorkplane);
86 }
87
88 SketchSolver_Group::~SketchSolver_Group()
89 {
90   myConstraints.clear();
91   // send the message that there is no more conflicting constraints
92   if (!myConflictingConstraints.empty()) {
93     sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
94     myConflictingConstraints.clear();
95   }
96 }
97
98 // ============================================================================
99 //  Function: changeConstraint
100 //  Class:    SketchSolver_Group
101 //  Purpose:  create/update the constraint in the group
102 // ============================================================================
103 bool SketchSolver_Group::changeConstraint(
104     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
105 {
106   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
107   if (isNewConstraint) {
108     // Add constraint to the current group
109     SolverConstraintPtr aConstraint = PlaneGCSSolver_Tools::createConstraint(theConstraint);
110     if (!aConstraint)
111       return false;
112     aConstraint->process(myStorage, myIsEventsBlocked);
113     if (!aConstraint->error().empty()) {
114       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
115         return false; // some attribute are not initialized yet, don't show message
116       Events_InfoMessage("SketchSolver_Group", aConstraint->error(), this).send();
117     }
118     myConstraints[theConstraint] = aConstraint;
119   }
120   else
121     myConstraints[theConstraint]->update();
122
123   // constraint is created/updated => reset stack of "multi" constraints updates
124   myMultiConstraintUpdateStack = 0;
125   return true;
126 }
127
128 bool SketchSolver_Group::updateSketch(CompositeFeaturePtr theSketch)
129 {
130   static const double THE_TOLERANCE = 1.e-7;
131   bool isChanged = theSketch != mySketch;
132
133   AttributePointPtr anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
134       theSketch->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
135   AttributeDirPtr aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
136       theSketch->attribute(SketchPlugin_Sketch::NORM_ID()));
137   AttributeDirPtr aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
138       theSketch->attribute(SketchPlugin_Sketch::DIRX_ID()));
139
140   isChanged = isChanged
141       || (mySketchOrigin && anOrigin && anOrigin->pnt()->distance(mySketchOrigin) > THE_TOLERANCE)
142       || (mySketchNormal && aNorm && aNorm->xyz()->distance(mySketchNormal->xyz()) > THE_TOLERANCE)
143       || (mySketchXDir && aDirX && aDirX->xyz()->distance(mySketchXDir->xyz()) > THE_TOLERANCE);
144
145   if (isChanged) {
146     mySketch = theSketch;
147     mySketchOrigin = anOrigin->pnt();
148     mySketchNormal = aNorm->dir();
149     mySketchXDir = aDirX->dir();
150
151     myStorage->notify(theSketch);
152   }
153   return true;
154 }
155
156 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
157 {
158   return myStorage->update(theFeature);
159 }
160
161 template <class Type>
162 static SolverConstraintPtr move(StoragePtr theStorage,
163                                 SolverPtr theSketchSolver,
164                                 int theSketchDOF,
165                                 bool theEventsBlocked,
166                                 Type theFeatureOrPoint,
167                                 const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
168                                 const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
169 {
170   bool isEntityExists = (theStorage->entity(theFeatureOrPoint).get() != 0);
171   if (theSketchDOF == 0 && isEntityExists) {
172     // avoid moving elements of fully constrained sketch
173     theStorage->refresh();
174     return SolverConstraintPtr();
175   }
176
177   // Create temporary Fixed constraint
178   std::shared_ptr<SketchSolver_ConstraintMovement> aConstraint =
179       PlaneGCSSolver_Tools::createMovementConstraint(theFeatureOrPoint);
180   if (aConstraint) {
181     SolverConstraintPtr(aConstraint)->process(theStorage, theEventsBlocked);
182     if (aConstraint->error().empty()) {
183       aConstraint->startPoint(theFrom);
184       theStorage->adjustParametrizationOfArcs();
185       theSketchSolver->initialize();
186       aConstraint->moveTo(theTo);
187       theStorage->setNeedToResolve(true);
188     } else
189       theStorage->notify(aConstraint->movedFeature());
190   }
191
192   return aConstraint;
193 }
194
195 bool SketchSolver_Group::moveFeature(FeaturePtr theFeature,
196                                      const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
197                                      const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
198 {
199   SolverConstraintPtr aConstraint =
200       move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked, theFeature, theFrom, theTo);
201   setTemporary(aConstraint);
202   return true;
203 }
204
205 bool SketchSolver_Group::movePoint(AttributePtr theAttribute,
206                                    const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
207                                    const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
208 {
209   SolverConstraintPtr aConstraint =
210       move(myStorage, mySketchSolver, myDOF, myIsEventsBlocked, theAttribute, theFrom, theTo);
211   setTemporary(aConstraint);
212   return true;
213 }
214
215 // ============================================================================
216 //  Function: resolveConstraints
217 //  Class:    SketchSolver_Group
218 //  Purpose:  solve the set of constraints for the current group
219 // ============================================================================
220 bool SketchSolver_Group::resolveConstraints()
221 {
222   static const int MAX_STACK_SIZE = 5;
223   // check the "Multi" constraints do not drop sketch into infinite loop
224   if (myMultiConstraintUpdateStack > MAX_STACK_SIZE) {
225     myMultiConstraintUpdateStack = 0;
226     myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
227     // generate error message due to loop update of the sketch
228     getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
229       ->setValue(SketchSolver_Error::INFINITE_LOOP());
230     sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
231     return false;
232   }
233
234   bool aResolved = false;
235   bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
236   if (myStorage->isNeedToResolve() &&
237       (!isGroupEmpty || !myConflictingConstraints.empty() ||
238         myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED)) {
239
240     PlaneGCSSolver_Solver::SolveStatus aResult = PlaneGCSSolver_Solver::STATUS_OK;
241     try {
242       if (!isGroupEmpty) {
243         myStorage->adjustParametrizationOfArcs();
244         aResult = mySketchSolver->solve();
245       }
246       if (aResult == PlaneGCSSolver_Solver::STATUS_FAILED &&
247           !myTempConstraints.empty()) {
248         mySketchSolver->undo();
249         removeTemporaryConstraints();
250         aResult = mySketchSolver->solve();
251       }
252       // check degenerated geometry after constraints resolving
253       if (aResult == PlaneGCSSolver_Solver::STATUS_OK)
254         aResult = myStorage->checkDegeneratedGeometry();
255     } catch (...) {
256       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())
257         ->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
258       if (myPrevResult == PlaneGCSSolver_Solver::STATUS_OK ||
259           myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
260         // the error message should be changed before sending the message
261         sendMessage(EVENT_SOLVER_FAILED);
262         myPrevResult = PlaneGCSSolver_Solver::STATUS_FAILED;
263       }
264       mySketchSolver->undo();
265       return false;
266     }
267     // solution succeeded, store results into correspondent attributes
268     if (aResult == PlaneGCSSolver_Solver::STATUS_OK ||
269         aResult == PlaneGCSSolver_Solver::STATUS_EMPTYSET) {
270       myStorage->setNeedToResolve(false);
271       myStorage->refresh();
272
273       // additional check that copied entities used in Mirror and other "Multi" constraints
274       // is not connected with their originals by constraints.
275       myMultiConstraintUpdateStack += 1;
276       aResolved = true;
277       if (myStorage->isNeedToResolve())
278         aResolved = resolveConstraints();
279
280       if (aResolved) {
281         myMultiConstraintUpdateStack -= 1;
282
283         if (myPrevResult != PlaneGCSSolver_Solver::STATUS_OK ||
284             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN) {
285           getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
286           std::set<ObjectPtr> aConflicting = myConflictingConstraints;
287           myConflictingConstraints.clear();
288           myPrevResult = PlaneGCSSolver_Solver::STATUS_OK;
289           // the error message should be changed before sending the message
290           sendMessage(EVENT_SOLVER_REPAIRED, aConflicting);
291         }
292       }
293
294       // show degrees of freedom
295       computeDoF();
296     } else {
297       mySketchSolver->undo();
298       if (!myConstraints.empty()) {
299         // the error message should be changed before sending the message
300         const std::string& aErrorMsg = aResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED ?
301                                        SketchSolver_Error::DEGENERATED_GEOMETRY() :
302                                        SketchSolver_Error::CONSTRAINTS();
303         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(aErrorMsg);
304         if (myPrevResult != aResult ||
305             myPrevResult == PlaneGCSSolver_Solver::STATUS_UNKNOWN ||
306             myPrevResult == PlaneGCSSolver_Solver::STATUS_FAILED) {
307           // Obtain list of conflicting constraints
308           std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
309
310           if (!myConflictingConstraints.empty()) {
311             std::set<ObjectPtr>::iterator anIt = aConflicting.begin();
312             for (; anIt != aConflicting.end(); ++anIt)
313               myConflictingConstraints.erase(*anIt);
314             if (!myConflictingConstraints.empty()) {
315               // some constraints does not conflict, send corresponding message
316               sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
317             }
318           }
319           myConflictingConstraints = aConflicting;
320           if (!myConflictingConstraints.empty())
321             sendMessage(EVENT_SOLVER_FAILED, myConflictingConstraints);
322           myPrevResult = aResult;
323         }
324       }
325
326       // show degrees of freedom only if the degenerated geometry appears
327       if (aResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED)
328         computeDoF();
329     }
330
331   }
332   else if (isGroupEmpty && isWorkplaneValid()) {
333     // clear error related to previously degenerated entities
334     if (myPrevResult == PlaneGCSSolver_Solver::STATUS_DEGENERATED) {
335       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
336       myPrevResult = PlaneGCSSolver_Solver::STATUS_OK;
337       // the error message should be changed before sending the message
338       myConflictingConstraints.clear();
339       sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
340     }
341
342     computeDoF();
343   }
344   removeTemporaryConstraints();
345   myStorage->setNeedToResolve(false);
346   return aResolved;
347 }
348
349 // ============================================================================
350 //  Function: computeDoF
351 //  Class:    SketchSolver_Group
352 //  Purpose:  compute DoF of the sketch and set corresponding field
353 // ============================================================================
354 void SketchSolver_Group::computeDoF()
355 {
356   std::string aDoFMsg;
357   static const std::string aMsgContext("Sketch");
358   int aDoF = mySketchSolver->dof();
359   /// "DoF = 0" content of string value is used in PartSet by Sketch edit
360   /// If it is changed, it should be corrected also there
361   //if (aDoF == 0) {
362   //  static const std::string aMsgDoF("Sketch is fully fixed (DoF = 0)");
363   //  aDoFMsg = Config_Translator::translate(aMsgContext, aMsgDoF);
364   //} else {
365   //  static const std::string aMsgDoF("DoF (degrees of freedom) = %1");
366   //  Events_InfoMessage aMsg(aMsgContext, aMsgDoF);
367   //  aMsg.addParameter(aDoF);
368   //  aDoFMsg = Config_Translator::translate(aMsg);
369   //}
370   //// store Unicode value for translated message about DoF
371   //size_t aLen = aDoFMsg.size();
372   //std::wstring aWStr(aLen, L'#');
373   //mbstowcs(&aWStr[0], aDoFMsg.c_str(), aLen);
374   //mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aWStr);
375
376   std::ostringstream aStr;
377   aStr << aDoF;
378   mySketch->string(SketchPlugin_Sketch::SOLVER_DOF())->setValue(aStr.str());
379
380   if (aDoF > 0 && myDOF <= 0)
381     sendMessage(EVENT_SKETCH_UNDER_CONSTRAINED, mySketch, aDoF);
382   else if (aDoF == 0 && myDOF != 0)
383     sendMessage(EVENT_SKETCH_FULLY_CONSTRAINED, mySketch, aDoF);
384   else if (aDoF < 0)
385     sendMessage(EVENT_SKETCH_OVER_CONSTRAINED, mySketch, aDoF);
386
387   myDOF = aDoF;
388 }
389
390 // ============================================================================
391 //  Function: repairConsistency
392 //  Class:    SketchSolver_Group
393 //  Purpose:  search removed entities and constraints
394 // ============================================================================
395 void SketchSolver_Group::repairConsistency()
396 {
397   if (!areConstraintsValid() || !myStorage->areFeaturesValid()) {
398     // remove invalid constraints
399     std::set<ConstraintPtr> anInvalidConstraints;
400     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
401     for (; aCIter != myConstraints.end(); ++aCIter) {
402       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
403         anInvalidConstraints.insert(aCIter->first);
404     }
405     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
406     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
407       removeConstraint(*aRemoveIt);
408
409     // remove invalid features
410     myStorage->removeInvalidEntities();
411
412     // show DoF
413     computeDoF();
414   }
415 }
416
417 // ============================================================================
418 //  Function: removeTemporaryConstraints
419 //  Class:    SketchSolver_Group
420 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
421 //            resolving the set of constraints
422 // ============================================================================
423 void SketchSolver_Group::removeTemporaryConstraints()
424 {
425   if (!myTempConstraints.empty()) {
426     mySketchSolver->removeConstraint(CID_MOVEMENT);
427
428     std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
429     for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
430       (*aTmpIt)->remove();
431
432     myTempConstraints.clear();
433   }
434
435   myStorage->setNeedToResolve(false);
436 }
437
438 // ============================================================================
439 //  Function: removeConstraint
440 //  Class:    SketchSolver_Group
441 //  Purpose:  remove constraint and all unused entities
442 // ============================================================================
443 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
444 {
445   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
446   for (; aCIter != myConstraints.end(); aCIter++)
447     if (aCIter->first == theConstraint) {
448       aCIter->second->remove(); // the constraint is not fully removed
449
450       // constraint is removed => reset stack of "multi" constraints updates
451       myMultiConstraintUpdateStack = 0;
452       break;
453     }
454   if (aCIter != myConstraints.end())
455     myConstraints.erase(aCIter);
456 }
457
458 // ============================================================================
459 //  Function: setTemporary
460 //  Class:    SketchSolver_Group
461 //  Purpose:  append given constraint to the group of temporary constraints
462 // ============================================================================
463 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
464 {
465   if (theConstraint)
466     myTempConstraints.insert(theConstraint);
467 }
468
469 // ============================================================================
470 //  Function: blockEvents
471 //  Class:    SketchSolver_Group
472 //  Purpose:  block or unblock events from features in this group
473 // ============================================================================
474 void SketchSolver_Group::blockEvents(bool isBlocked)
475 {
476   if (myIsEventsBlocked == isBlocked)
477     return;
478
479   // block/unblock events from the features in the storage
480   myStorage->blockEvents(isBlocked);
481
482   // block/unblock events from constraints
483   ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
484   for (; aCIt != myConstraints.end(); ++aCIt)
485     aCIt->second->blockEvents(isBlocked);
486
487   myIsEventsBlocked = isBlocked;
488 }
489
490 bool SketchSolver_Group::areConstraintsValid() const
491 {
492   // Check the constraints are valid
493   ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
494   for (; aCIter != myConstraints.end(); ++aCIter)
495     if (!aCIter->first->data() || !aCIter->first->data()->isValid())
496       return false;
497   return true;
498 }
499
500 void SketchSolver_Group::underconstrainedFeatures(std::set<FeaturePtr>& theFeatures) const
501 {
502   myStorage->getUnderconstrainedGeometry(theFeatures);
503 }