Salome HOME
Merge remote-tracking branch 'remotes/origin/occ/bsplines'
[modules/shaper.git] / src / SketchSolver / SketchSolver_Manager.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_Manager.h"
21 #include "SketchSolver_Error.h"
22
23 #include <Events_Loop.h>
24 #include <GeomDataAPI_Point2D.h>
25 #include <GeomDataAPI_Point2DArray.h>
26 #include <ModelAPI_Events.h>
27 #include <ModelAPI_ResultConstruction.h>
28 #include <ModelAPI_Session.h>
29 #include <ModelAPI_Validator.h>
30 #include <SketchPlugin_Sketch.h>
31
32 /// Global constraint manager object
33 static SketchSolver_Manager* myManager = SketchSolver_Manager::instance();
34
35 /// \brief Verifies is the feature valid
36 static bool isFeatureValid(FeaturePtr theFeature)
37 {
38   if (!theFeature || !theFeature->data() || !theFeature->data()->isValid())
39     return false;
40
41   SessionPtr aMgr = ModelAPI_Session::get();
42   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
43   return aFactory->validate(theFeature);
44 }
45
46 typedef std::map<int, std::shared_ptr<SketchPlugin_Feature>> IndexedFeatureMap;
47
48 static void featuresOrderedByCreation(const std::set<ObjectPtr>& theOriginalFeatures,
49                                       IndexedFeatureMap& theOrderedFeatures)
50 {
51   std::set<ObjectPtr>::iterator aFeatIter = theOriginalFeatures.begin();
52   for (; aFeatIter != theOriginalFeatures.end(); aFeatIter++) {
53     std::shared_ptr<SketchPlugin_Feature> aFeature =
54         std::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
55     if (aFeature && !aFeature->isMacro() && aFeature->data() && aFeature->data()->isValid()) {
56       theOrderedFeatures[aFeature->data()->featureId()] = aFeature;
57     }
58   }
59 }
60
61 static void featuresOrderedByType(const std::set<ObjectPtr>& theOriginalFeatures,
62                                   IndexedFeatureMap& theOrderedFeatures,
63                                   CompositeFeaturePtr& theSketch)
64 {
65   int aFeatureIndex = 0;
66   int aConstraintIndex = (int)theOriginalFeatures.size();
67
68   std::set<ObjectPtr>::iterator aFeatIter = theOriginalFeatures.begin();
69   for (; aFeatIter != theOriginalFeatures.end(); aFeatIter++) {
70     std::shared_ptr<SketchPlugin_Feature> aFeature =
71         std::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
72     if (aFeature) {
73       if (!aFeature->isMacro() && aFeature->data() && aFeature->data()->isValid()) {
74         std::shared_ptr<SketchPlugin_Constraint> aConstraint =
75             std::dynamic_pointer_cast<SketchPlugin_Constraint>(aFeature);
76         if (aConstraint)
77           theOrderedFeatures[++aConstraintIndex] = aFeature;
78         else
79           theOrderedFeatures[++aFeatureIndex] = aFeature;
80       }
81     }
82     else {
83       CompositeFeaturePtr aSketch =
84           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aFeatIter);
85       if (aSketch && aSketch->getKind() == SketchPlugin_Sketch::ID())
86         theSketch = aSketch;
87     }
88   }
89 }
90
91 static void setPoint(AttributePtr theAttribute,
92                      const int thePointIndex,
93                      const std::shared_ptr<GeomAPI_Pnt2d> theValue)
94 {
95   AttributePoint2DPtr aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
96   AttributePoint2DArrayPtr aPointArrayAttr =
97       std::dynamic_pointer_cast<GeomDataAPI_Point2DArray>(theAttribute);
98   if (aPointAttr)
99     aPointAttr->setValue(theValue);
100   else if (aPointArrayAttr && thePointIndex >= 0)
101     aPointArrayAttr->setPnt(thePointIndex, theValue);
102 }
103
104
105
106 // ========================================================
107 // ========= SketchSolver_Manager ===============
108 // ========================================================
109 SketchSolver_Manager* SketchSolver_Manager::instance()
110 {
111   static SketchSolver_Manager* mySelf = 0; // Self pointer to implement singleton functionality
112   if (!mySelf)
113     mySelf = new SketchSolver_Manager();
114   return mySelf;
115 }
116
117 SketchSolver_Manager::SketchSolver_Manager()
118 {
119   myGroups.clear();
120   myIsComputed = false;
121
122   // Register in event loop
123   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
124   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
125   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED));
126   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_MOVED));
127
128   ////Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_FAILED));
129   ////Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_REPAIRED));
130   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SKETCH_PREPARED));
131   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_GET_DOF_OBJECTS));
132 }
133
134 SketchSolver_Manager::~SketchSolver_Manager()
135 {
136   myGroups.clear();
137 }
138
139 bool SketchSolver_Manager::groupMessages()
140 {
141   return true;
142 }
143
144 // ============================================================================
145 //  Function: processEvent
146 //  Purpose:  listen the event loop and process the message
147 // ============================================================================
148 void SketchSolver_Manager::processEvent(
149   const std::shared_ptr<Events_Message>& theMessage)
150 {
151   bool needToResolve = false;
152   bool isUpdateFlushed = false;
153   bool isMovedEvt = false;
154
155   static const Events_ID aCreatedEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
156   static const Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
157   static const Events_ID aSketchPreparedEvent = Events_Loop::eventByName(EVENT_SKETCH_PREPARED);
158   // sketch is prepared for resolve: all the needed events
159   // are collected and must be processed by the solver
160   if (theMessage->eventID() == aSketchPreparedEvent) {
161     flushGrouped(anUpdateEvent);
162     needToResolve = true;
163   }
164
165   if (myIsComputed)
166     return;
167   myIsComputed = true;
168
169   if (theMessage->eventID() == aCreatedEvent || theMessage->eventID() == anUpdateEvent) {
170     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
171         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
172
173     isUpdateFlushed = stopSendUpdate();
174
175     // update sketch features only
176     const std::set<ObjectPtr>& aFeatures = anUpdateMsg->objects();
177     IndexedFeatureMap anOrderedFeatures;
178     CompositeFeaturePtr aSketchFeature;
179     // try to keep order as features were created if there are several created features: #2229
180     if (theMessage->eventID() == aCreatedEvent && aFeatures.size() > 1) {
181       featuresOrderedByCreation(aFeatures, anOrderedFeatures);
182     } else { // order is not important, just process features before constraints
183       featuresOrderedByType(aFeatures, anOrderedFeatures, aSketchFeature);
184     }
185
186     IndexedFeatureMap::iterator aFeat;
187     for (aFeat = anOrderedFeatures.begin(); aFeat != anOrderedFeatures.end(); aFeat++) {
188       updateFeature(aFeat->second);
189     }
190     updateSketch(aSketchFeature);
191
192   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED)) {
193     std::shared_ptr<ModelAPI_ObjectMovedMessage> aMoveMsg =
194         std::dynamic_pointer_cast<ModelAPI_ObjectMovedMessage>(theMessage);
195
196     ObjectPtr aMovedObject = aMoveMsg->movedObject();
197     AttributePtr aMovedAttribute = aMoveMsg->movedAttribute();
198     int aMovedPoint = aMoveMsg->movedPointIndex();
199
200     const std::shared_ptr<GeomAPI_Pnt2d>& aFrom = aMoveMsg->originalPosition();
201     const std::shared_ptr<GeomAPI_Pnt2d>& aTo = aMoveMsg->currentPosition();
202
203     if (aMovedObject) {
204       FeaturePtr aMovedFeature = ModelAPI_Feature::feature(aMovedObject);
205       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
206           std::dynamic_pointer_cast<SketchPlugin_Feature>(aMovedFeature);
207       if (aSketchFeature && !aSketchFeature->isMacro())
208         needToResolve = moveFeature(aSketchFeature, aFrom, aTo);
209     } else if (aMovedAttribute)
210       needToResolve = moveAttribute(aMovedAttribute, aMovedPoint, aFrom, aTo);
211
212   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
213     std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleteMsg =
214       std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
215     const std::list<std::pair<std::shared_ptr<ModelAPI_Document>, std::string>>& aFeatureGroups =
216       aDeleteMsg->groups();
217
218     // Find SketchPlugin_Sketch::ID() in groups.
219     // The constraint groups should be updated when an object removed from Sketch
220     std::list<std::pair<std::shared_ptr<ModelAPI_Document>, std::string>>::const_iterator aFGrIter;
221     for (aFGrIter = aFeatureGroups.begin(); aFGrIter != aFeatureGroups.end(); aFGrIter++)
222       if (aFGrIter->second == ModelAPI_ResultConstruction::group() ||
223         aFGrIter->second == ModelAPI_Feature::group())
224         break;
225
226     if (aFGrIter != aFeatureGroups.end()) {
227       std::list<SketchGroupPtr>::iterator aGroupIter = myGroups.begin();
228       while (aGroupIter != myGroups.end()) {
229         if (!(*aGroupIter)->isWorkplaneValid()) {  // the group should be removed
230           std::list<SketchGroupPtr>::iterator aRemoveIt = aGroupIter++;
231           myGroups.erase(aRemoveIt);
232           continue;
233         }
234
235         (*aGroupIter)->repairConsistency();
236         ++aGroupIter;
237       }
238     }
239     myIsComputed = false;
240   }
241   else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_GET_DOF_OBJECTS)) {
242     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
243       std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
244     std::set<ObjectPtr> aObjects = anUpdateMsg->objects();
245     if (aObjects.size() == 1) {
246       std::set<ObjectPtr>::const_iterator aIt;
247       for (aIt = aObjects.cbegin(); aIt != aObjects.cend(); aIt++) {
248         CompositeFeaturePtr aFeature =
249             std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aIt);
250         if (aFeature) {
251           SketchGroupPtr aGroup = findGroup(aFeature);
252
253           std::set<ObjectPtr> aFreeFeatures;
254           aGroup->underconstrainedFeatures(aFreeFeatures);
255
256           std::list<ObjectPtr> aFeatures;
257           std::set<ObjectPtr>::const_iterator aIt;
258           for (aIt = aFreeFeatures.cbegin(); aIt != aFreeFeatures.cend(); ++aIt) {
259             aFeatures.push_back(*aIt);
260           }
261
262           // send features to GUI
263           static const Events_ID anEvent = Events_Loop::eventByName(EVENT_DOF_OBJECTS);
264           ModelAPI_EventCreator::get()->sendUpdated(aFeatures, anEvent);
265           Events_Loop::loop()->flush(anEvent);
266         }
267       }
268     }
269   }
270
271   // resolve constraints if needed
272   bool needToUpdate = needToResolve && resolveConstraints();
273   releaseFeaturesIfEventsBlocked();
274
275   // Features may be updated => now send events, but for all changed at once
276   if (isUpdateFlushed)
277     allowSendUpdate();
278
279   myIsComputed = false;
280
281   // send update for movement in any case
282   if (needToUpdate || isMovedEvt)
283     Events_Loop::loop()->flush(anUpdateEvent);
284 }
285
286 // ============================================================================
287 //  Function: updateSketch
288 //  Purpose:  update sketch plane in appropriate group
289 // ============================================================================
290 bool SketchSolver_Manager::updateSketch(const CompositeFeaturePtr& theSketch)
291 {
292   if (!theSketch)
293     return true;
294
295   bool isOk = true;
296   std::list<SketchGroupPtr>::const_iterator aGroupIt;
297   for (aGroupIt = myGroups.begin(); aGroupIt != myGroups.end(); ++aGroupIt)
298     if ((*aGroupIt)->getWorkplane() == theSketch) {
299       (*aGroupIt)->updateSketch(theSketch);
300       break;
301     }
302   return isOk;
303 }
304
305 // ============================================================================
306 //  Function: updateFeature
307 //  Purpose:  create/update constraint or feature in appropriate group
308 // ============================================================================
309 bool SketchSolver_Manager::updateFeature(const std::shared_ptr<SketchPlugin_Feature>& theFeature)
310 {
311   // Check feature validity and find a group to place it.
312   // If the feature is not valid, the returned group will be empty.
313   // This will protect to deal with wrong (not fully initialized) features.
314   SketchGroupPtr aGroup = findGroup(theFeature);
315   if (!aGroup)
316     return false;
317   aGroup->blockEvents(true);
318
319   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
320       std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
321
322   bool isOk = false;
323   if (aConstraint)
324     isOk = aGroup->changeConstraint(aConstraint);
325   else
326     isOk = aGroup->updateFeature(theFeature);
327   return isOk;
328 }
329
330 // ============================================================================
331 //  Function: moveFeature
332 //  Purpose:  move given feature in appropriate group
333 // ============================================================================
334 bool SketchSolver_Manager::moveFeature(
335     const std::shared_ptr<SketchPlugin_Feature>& theMovedFeature,
336     const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
337     const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
338 {
339   SketchGroupPtr aGroup = findGroup(theMovedFeature);
340   if (!aGroup)
341     return false;
342
343   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
344       std::dynamic_pointer_cast<SketchPlugin_Constraint>(theMovedFeature);
345   if (aConstraint)
346   {
347     std::shared_ptr<GeomDataAPI_Point2D> aPntAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>
348       (aConstraint->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT()));
349     if (aPntAttr)
350     {
351       aPntAttr->setValue(theTo);
352       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
353     }
354     return true;
355   }
356
357   aGroup->blockEvents(true);
358   return aGroup->moveFeature(theMovedFeature, theFrom, theTo);
359 }
360
361 // ============================================================================
362 //  Function: moveAttribute
363 //  Purpose:  move given attribute in appropriate group
364 // ============================================================================
365 bool SketchSolver_Manager::moveAttribute(
366     const std::shared_ptr<ModelAPI_Attribute>& theMovedAttribute,
367     const int theMovedPointIndex,
368     const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
369     const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
370 {
371   FeaturePtr anOwner = ModelAPI_Feature::feature(theMovedAttribute->owner());
372   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
373       std::dynamic_pointer_cast<SketchPlugin_Constraint>(anOwner);
374   if (aConstraint)
375   {
376     setPoint(theMovedAttribute, theMovedPointIndex, theTo);
377     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
378     return true;
379   }
380
381   std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
382       std::dynamic_pointer_cast<SketchPlugin_Feature>(anOwner);
383   SketchGroupPtr aGroup;
384   if (aSketchFeature)
385     aGroup = findGroup(aSketchFeature);
386   if (!aGroup) {
387     setPoint(theMovedAttribute, theMovedPointIndex, theTo);
388     return false;
389   }
390
391   aGroup->blockEvents(true);
392   return aGroup->movePoint(theMovedAttribute, theMovedPointIndex, theFrom, theTo);
393 }
394
395 // ============================================================================
396 //  Function: findGroup
397 //  Purpose:  search groups of entities interacting with given feature
398 // ============================================================================
399 SketchGroupPtr SketchSolver_Manager::findGroup(
400   std::shared_ptr<SketchPlugin_Feature> theFeature)
401 {
402   if (!isFeatureValid(theFeature))
403     return SketchGroupPtr(); // do not process wrong features
404
405   // Obtain sketch, containing the feature
406   CompositeFeaturePtr aSketch;
407   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
408   std::set<AttributePtr>::const_iterator aRefIt = aRefsList.begin();
409   for (; aRefIt != aRefsList.end(); ++aRefIt) {
410     FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
411     if (anOwner && anOwner->getKind() == SketchPlugin_Sketch::ID()) {
412       aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(anOwner);
413       break;
414     }
415   }
416   return findGroup(aSketch);
417 }
418
419 SketchGroupPtr SketchSolver_Manager::findGroup(CompositeFeaturePtr theSketch)
420 {
421   if (!theSketch)
422     return SketchGroupPtr(); // not a sketch's feature
423
424   std::list<SketchGroupPtr>::const_iterator aGroupIt;
425   for (aGroupIt = myGroups.begin(); aGroupIt != myGroups.end(); ++aGroupIt)
426     if ((*aGroupIt)->getWorkplane() == theSketch)
427       return *aGroupIt;
428
429   // group for the sketch does not created yet
430   SketchGroupPtr aNewGroup = SketchGroupPtr(new SketchSolver_Group(theSketch));
431   myGroups.push_back(aNewGroup);
432   return aNewGroup;
433 }
434
435 // ============================================================================
436 //  Function: resolveConstraints
437 //  Purpose:  change entities according to available constraints
438 // ============================================================================
439 bool SketchSolver_Manager::resolveConstraints()
440 {
441   bool needToUpdate = false;
442   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
443   for (; aGroupIter != myGroups.end(); ++aGroupIter) {
444     if ((*aGroupIter)->resolveConstraints())
445       needToUpdate = true;
446   }
447   return needToUpdate;
448 }
449
450 void SketchSolver_Manager::releaseFeaturesIfEventsBlocked() const
451 {
452   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
453   for (; aGroupIter != myGroups.end(); ++aGroupIter)
454     (*aGroupIter)->blockEvents(false);
455 }
456
457 bool SketchSolver_Manager::stopSendUpdate() const
458 {
459 static const Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
460   // to avoid redisplay of each segment on update by solver one by one in the viewer
461   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
462   if (isUpdateFlushed) {
463     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
464   }
465   return isUpdateFlushed;
466 }
467
468 void SketchSolver_Manager::allowSendUpdate() const
469 {
470   Events_Loop::loop()->setFlushed(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), true);
471 }