Salome HOME
Merge branch 'Results_Hierarchy'
[modules/shaper.git] / src / SketchSolver / SketchSolver_Manager.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_Manager.h"
22 #include "SketchSolver_Error.h"
23
24 #include <Events_Loop.h>
25 #include <GeomDataAPI_Point2D.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
47
48 // ========================================================
49 // ========= SketchSolver_Manager ===============
50 // ========================================================
51 SketchSolver_Manager* SketchSolver_Manager::instance()
52 {
53   static SketchSolver_Manager* mySelf = 0; // Self pointer to implement singleton functionality
54   if (!mySelf)
55     mySelf = new SketchSolver_Manager();
56   return mySelf;
57 }
58
59 SketchSolver_Manager::SketchSolver_Manager()
60 {
61   myGroups.clear();
62   myIsComputed = false;
63
64   // Register in event loop
65   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
66   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
67   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED));
68   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_MOVED));
69
70   ////Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_FAILED));
71   ////Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_REPAIRED));
72   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SKETCH_PREPARED));
73 }
74
75 SketchSolver_Manager::~SketchSolver_Manager()
76 {
77   myGroups.clear();
78 }
79
80 bool SketchSolver_Manager::groupMessages()
81 {
82   return true;
83 }
84
85 // ============================================================================
86 //  Function: processEvent
87 //  Purpose:  listen the event loop and process the message
88 // ============================================================================
89 void SketchSolver_Manager::processEvent(
90   const std::shared_ptr<Events_Message>& theMessage)
91 {
92   bool needToResolve = false;
93   bool isUpdateFlushed = false;
94   bool isMovedEvt = false;
95
96   static const Events_ID aCreatedEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
97   static const Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
98   static const Events_ID aSketchPreparedEvent = Events_Loop::eventByName(EVENT_SKETCH_PREPARED);
99   // sketch is prepared for resolve: all the needed events
100   // are collected and must be processed by the solver
101   if (theMessage->eventID() == aSketchPreparedEvent) {
102     flushGrouped(anUpdateEvent);
103     needToResolve = true;
104   }
105
106   if (myIsComputed)
107     return;
108   myIsComputed = true;
109
110   if (theMessage->eventID() == aCreatedEvent || theMessage->eventID() == anUpdateEvent) {
111     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
112         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
113
114     isUpdateFlushed = stopSendUpdate();
115
116     // update sketch features only
117     const std::set<ObjectPtr>& aFeatures = anUpdateMsg->objects();
118     // try to keep order as features were created if there are several created features: #2229
119     if (theMessage->eventID() == aCreatedEvent && aFeatures.size() > 1) {
120       std::map<int, std::shared_ptr<SketchPlugin_Feature>> anOrderedFeatures;
121       std::set<ObjectPtr>::iterator aFeatIter;
122       for (aFeatIter = aFeatures.begin(); aFeatIter != aFeatures.end(); aFeatIter++) {
123         std::shared_ptr<SketchPlugin_Feature> aFeature =
124             std::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
125         if (aFeature && !aFeature->isMacro() && aFeature->data() && aFeature->data()->isValid()) {
126           anOrderedFeatures[aFeature->data()->featureId()] = aFeature;
127         }
128       }
129       std::map<int, std::shared_ptr<SketchPlugin_Feature>>::iterator aFeat;
130       for(aFeat = anOrderedFeatures.begin(); aFeat != anOrderedFeatures.end(); aFeat++) {
131         updateFeature(aFeat->second);
132       }
133     } else { // order is not important
134       std::set<ObjectPtr>::iterator aFeatIter;
135       for (aFeatIter = aFeatures.begin(); aFeatIter != aFeatures.end(); aFeatIter++) {
136         std::shared_ptr<SketchPlugin_Feature> aFeature =
137             std::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
138         if (aFeature && !aFeature->isMacro())
139           updateFeature(aFeature);
140       }
141     }
142
143   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED)) {
144     std::shared_ptr<ModelAPI_ObjectMovedMessage> aMoveMsg =
145         std::dynamic_pointer_cast<ModelAPI_ObjectMovedMessage>(theMessage);
146
147     ObjectPtr aMovedObject = aMoveMsg->movedObject();
148     std::shared_ptr<GeomDataAPI_Point2D> aMovedPoint =
149         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aMoveMsg->movedAttribute());
150
151     const std::shared_ptr<GeomAPI_Pnt2d>& aFrom = aMoveMsg->originalPosition();
152     const std::shared_ptr<GeomAPI_Pnt2d>& aTo = aMoveMsg->currentPosition();
153
154     if (aMovedObject) {
155       FeaturePtr aMovedFeature = ModelAPI_Feature::feature(aMovedObject);
156       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
157           std::dynamic_pointer_cast<SketchPlugin_Feature>(aMovedFeature);
158       if (aSketchFeature && !aSketchFeature->isMacro())
159         needToResolve = moveFeature(aSketchFeature, aFrom, aTo);
160     } else if (aMovedPoint)
161       needToResolve = moveAttribute(aMovedPoint, aFrom, aTo);
162
163   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
164     std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleteMsg =
165       std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
166     const std::list<std::pair<std::shared_ptr<ModelAPI_Document>, std::string>>& aFeatureGroups =
167       aDeleteMsg->groups();
168
169     // Find SketchPlugin_Sketch::ID() in groups.
170     // The constraint groups should be updated when an object removed from Sketch
171     std::list<std::pair<std::shared_ptr<ModelAPI_Document>, std::string>>::const_iterator aFGrIter;
172     for (aFGrIter = aFeatureGroups.begin(); aFGrIter != aFeatureGroups.end(); aFGrIter++)
173       if (aFGrIter->second == ModelAPI_ResultConstruction::group() ||
174         aFGrIter->second == ModelAPI_Feature::group())
175         break;
176
177     if (aFGrIter != aFeatureGroups.end()) {
178       std::list<SketchGroupPtr>::iterator aGroupIter = myGroups.begin();
179       while (aGroupIter != myGroups.end()) {
180         if (!(*aGroupIter)->isWorkplaneValid()) {  // the group should be removed
181           std::list<SketchGroupPtr>::iterator aRemoveIt = aGroupIter++;
182           myGroups.erase(aRemoveIt);
183           continue;
184         }
185
186         (*aGroupIter)->repairConsistency();
187         ++aGroupIter;
188       }
189     }
190     myIsComputed = false;
191   }
192
193   // resolve constraints if needed
194   bool needToUpdate = needToResolve && resolveConstraints();
195   releaseFeaturesIfEventsBlocked();
196
197   // Features may be updated => now send events, but for all changed at once
198   if (isUpdateFlushed)
199     allowSendUpdate();
200
201   myIsComputed = false;
202
203   // send update for movement in any case
204   if (needToUpdate || isMovedEvt)
205     Events_Loop::loop()->flush(anUpdateEvent);
206 }
207
208 // ============================================================================
209 //  Function: updateFeature
210 //  Purpose:  create/update constraint or feature in appropriate group
211 // ============================================================================
212 bool SketchSolver_Manager::updateFeature(const std::shared_ptr<SketchPlugin_Feature>& theFeature)
213 {
214   // Check feature validity and find a group to place it.
215   // If the feature is not valid, the returned group will be empty.
216   // This will protect to deal with wrong (not fully initialized) features.
217   SketchGroupPtr aGroup = findGroup(theFeature);
218   if (!aGroup)
219     return false;
220   aGroup->blockEvents(true);
221
222   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
223       std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
224
225   bool isOk = false;
226   if (aConstraint)
227     isOk = aGroup->changeConstraint(aConstraint);
228   else
229     isOk = aGroup->updateFeature(theFeature);
230   return isOk;
231 }
232
233 // ============================================================================
234 //  Function: moveFeature
235 //  Purpose:  move given feature in appropriate group
236 // ============================================================================
237 bool SketchSolver_Manager::moveFeature(
238     const std::shared_ptr<SketchPlugin_Feature>& theMovedFeature,
239     const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
240     const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
241 {
242   SketchGroupPtr aGroup = findGroup(theMovedFeature);
243   if (!aGroup)
244     return false;
245
246   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
247       std::dynamic_pointer_cast<SketchPlugin_Constraint>(theMovedFeature);
248   if (aConstraint)
249   {
250     std::shared_ptr<GeomDataAPI_Point2D> aPntAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>
251       (aConstraint->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT()));
252     if (aPntAttr)
253     {
254       aPntAttr->setValue(theTo);
255       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
256     }
257     return true;
258   }
259
260   aGroup->blockEvents(true);
261   return aGroup->moveFeature(theMovedFeature, theFrom, theTo);
262 }
263
264 // ============================================================================
265 //  Function: moveAttribute
266 //  Purpose:  move given attribute in appropriate group
267 // ============================================================================
268 bool SketchSolver_Manager::moveAttribute(
269     const std::shared_ptr<GeomDataAPI_Point2D>& theMovedAttribute,
270     const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
271     const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
272 {
273   FeaturePtr anOwner = ModelAPI_Feature::feature(theMovedAttribute->owner());
274   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
275       std::dynamic_pointer_cast<SketchPlugin_Constraint>(anOwner);
276   if (aConstraint)
277   {
278     theMovedAttribute->setValue(theTo);
279     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
280     return true;
281   }
282
283   std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
284       std::dynamic_pointer_cast<SketchPlugin_Feature>(anOwner);
285   SketchGroupPtr aGroup;
286   if (aSketchFeature)
287     aGroup = findGroup(aSketchFeature);
288   if (!aGroup) {
289     theMovedAttribute->setValue(theTo);
290     return false;
291   }
292
293   aGroup->blockEvents(true);
294   return aGroup->movePoint(theMovedAttribute, theFrom, theTo);
295 }
296
297 // ============================================================================
298 //  Function: findGroup
299 //  Purpose:  search groups of entities interacting with given feature
300 // ============================================================================
301 SketchGroupPtr SketchSolver_Manager::findGroup(
302     std::shared_ptr<SketchPlugin_Feature> theFeature)
303 {
304   if (!isFeatureValid(theFeature))
305     return SketchGroupPtr(); // do not process wrong features
306
307   // Obtain sketch, containing the feature
308   CompositeFeaturePtr aSketch;
309   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
310   std::set<AttributePtr>::const_iterator aRefIt = aRefsList.begin();
311   for (; aRefIt != aRefsList.end(); ++aRefIt) {
312     FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
313     if (anOwner && anOwner->getKind() == SketchPlugin_Sketch::ID()) {
314       aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(anOwner);
315       break;
316     }
317   }
318
319   if (!aSketch)
320     return SketchGroupPtr(); // not a sketch's feature
321
322   std::list<SketchGroupPtr>::const_iterator aGroupIt;
323   for (aGroupIt = myGroups.begin(); aGroupIt != myGroups.end(); ++aGroupIt)
324     if ((*aGroupIt)->getWorkplane() == aSketch)
325       return *aGroupIt;
326
327   // group for the sketch does not created yet
328   SketchGroupPtr aNewGroup = SketchGroupPtr(new SketchSolver_Group(aSketch));
329   myGroups.push_back(aNewGroup);
330   return aNewGroup;
331 }
332
333 // ============================================================================
334 //  Function: resolveConstraints
335 //  Purpose:  change entities according to available constraints
336 // ============================================================================
337 bool SketchSolver_Manager::resolveConstraints()
338 {
339   bool needToUpdate = false;
340   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
341   for (; aGroupIter != myGroups.end(); ++aGroupIter) {
342     if ((*aGroupIter)->resolveConstraints())
343       needToUpdate = true;
344   }
345   return needToUpdate;
346 }
347
348 void SketchSolver_Manager::releaseFeaturesIfEventsBlocked() const
349 {
350   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
351   for (; aGroupIter != myGroups.end(); ++aGroupIter)
352     (*aGroupIter)->blockEvents(false);
353 }
354
355 bool SketchSolver_Manager::stopSendUpdate() const
356 {
357 static const Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
358   // to avoid redisplay of each segment on update by solver one by one in the viewer
359   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
360   if (isUpdateFlushed) {
361     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
362   }
363   return isUpdateFlushed;
364 }
365
366 void SketchSolver_Manager::allowSendUpdate() const
367 {
368   Events_Loop::loop()->setFlushed(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), true);
369 }