Salome HOME
Merge remote-tracking branch 'remotes/origin/master'
[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 <ModelAPI_Events.h>
26 #include <ModelAPI_ResultConstruction.h>
27 #include <ModelAPI_Session.h>
28 #include <ModelAPI_Validator.h>
29 #include <SketchPlugin_Sketch.h>
30
31 /// Global constraint manager object
32 static SketchSolver_Manager* myManager = SketchSolver_Manager::instance();
33
34 /// \brief Verifies is the feature valid
35 static bool isFeatureValid(FeaturePtr theFeature)
36 {
37   if (!theFeature || !theFeature->data() || !theFeature->data()->isValid())
38     return false;
39
40   SessionPtr aMgr = ModelAPI_Session::get();
41   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
42   return aFactory->validate(theFeature);
43 }
44
45
46
47 // ========================================================
48 // ========= SketchSolver_Manager ===============
49 // ========================================================
50 SketchSolver_Manager* SketchSolver_Manager::instance()
51 {
52   static SketchSolver_Manager* mySelf = 0; // Self pointer to implement singleton functionality
53   if (!mySelf)
54     mySelf = new SketchSolver_Manager();
55   return mySelf;
56 }
57
58 SketchSolver_Manager::SketchSolver_Manager()
59 {
60   myGroups.clear();
61   myIsComputed = false;
62
63   // Register in event loop
64   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
65   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
66   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED));
67   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_MOVED));
68
69   ////Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_FAILED));
70   ////Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_REPAIRED));
71   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SKETCH_PREPARED));
72 }
73
74 SketchSolver_Manager::~SketchSolver_Manager()
75 {
76   myGroups.clear();
77 }
78
79 bool SketchSolver_Manager::groupMessages()
80 {
81   return true;
82 }
83
84 // ============================================================================
85 //  Function: processEvent
86 //  Purpose:  listen the event loop and process the message
87 // ============================================================================
88 void SketchSolver_Manager::processEvent(
89   const std::shared_ptr<Events_Message>& theMessage)
90 {
91   bool needToResolve = false;
92   bool isUpdateFlushed = false;
93   bool isMovedEvt = false;
94
95   static const Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
96   static const Events_ID aSketchPreparedEvent = Events_Loop::eventByName(EVENT_SKETCH_PREPARED);
97   // sketch is prepared for resolve: all the needed events
98   // are collected and must be processed by the solver
99   if (theMessage->eventID() == aSketchPreparedEvent) {
100     flushGrouped(anUpdateEvent);
101     needToResolve = true;
102   }
103
104   if (myIsComputed)
105     return;
106   myIsComputed = true;
107
108   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED)
109       || theMessage->eventID() == anUpdateEvent
110       || theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED)) {
111     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
112         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
113     std::set<ObjectPtr> aFeatures = anUpdateMsg->objects();
114
115     isUpdateFlushed = stopSendUpdate();
116
117     isMovedEvt = theMessage->eventID()
118           == Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED);
119
120     // Shows that the message has at least one feature applicable for solver
121     bool hasProperFeature = false;
122
123     // update sketch features only
124     std::set<ObjectPtr>::iterator aFeatIter;
125     for (aFeatIter = aFeatures.begin(); aFeatIter != aFeatures.end(); aFeatIter++) {
126       std::shared_ptr<SketchPlugin_Feature> aFeature =
127           std::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
128       if (!aFeature || aFeature->isMacro())
129         continue;
130
131       hasProperFeature = updateFeature(aFeature, isMovedEvt) || hasProperFeature;
132     }
133
134     if (isMovedEvt && hasProperFeature)
135       needToResolve = true;
136
137   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
138     std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleteMsg =
139       std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
140     const std::set<std::string>& aFeatureGroups = aDeleteMsg->groups();
141
142     // Find SketchPlugin_Sketch::ID() in groups.
143     // The constraint groups should be updated when an object removed from Sketch
144     std::set<std::string>::const_iterator aFGrIter;
145     for (aFGrIter = aFeatureGroups.begin(); aFGrIter != aFeatureGroups.end(); aFGrIter++)
146       if (aFGrIter->compare(ModelAPI_ResultConstruction::group()) == 0 ||
147           aFGrIter->compare(ModelAPI_Feature::group()) == 0)
148         break;
149
150     if (aFGrIter != aFeatureGroups.end()) {
151       std::list<SketchGroupPtr>::iterator aGroupIter = myGroups.begin();
152       while (aGroupIter != myGroups.end()) {
153         if (!(*aGroupIter)->isWorkplaneValid()) {  // the group should be removed
154           std::list<SketchGroupPtr>::iterator aRemoveIt = aGroupIter++;
155           myGroups.erase(aRemoveIt);
156           continue;
157         }
158
159         (*aGroupIter)->repairConsistency();
160         ++aGroupIter;
161       }
162     }
163     myIsComputed = false;
164   }
165
166   // resolve constraints if needed
167   bool needToUpdate = needToResolve && resolveConstraints();
168   releaseFeaturesIfEventsBlocked();
169
170   // Features may be updated => now send events, but for all changed at once
171   if (isUpdateFlushed)
172     allowSendUpdate();
173
174   myIsComputed = false;
175
176   // send update for movement in any case
177   if (needToUpdate || isMovedEvt)
178     Events_Loop::loop()->flush(anUpdateEvent);
179 }
180
181 // ============================================================================
182 //  Function: changeConstraintOrEntity
183 //  Purpose:  create/update the constraint or the feature and place it into appropriate group
184 // ============================================================================
185 bool SketchSolver_Manager::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature,
186                                          bool theMoved)
187 {
188   // Check feature validity and find a group to place it.
189   // If the feature is not valid, the returned group will be empty.
190   // This will protect to deal with wrong (not fully initialized) features.
191   SketchGroupPtr aGroup = findGroup(theFeature);
192   if (!aGroup)
193     return false;
194   aGroup->blockEvents(true);
195
196   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
197       std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
198
199   bool isOk = false;
200   if (aConstraint)
201     isOk = aGroup->changeConstraint(aConstraint);
202   else if (theMoved)
203     isOk = aGroup->moveFeature(theFeature);
204   else
205     isOk = aGroup->updateFeature(theFeature);
206   return isOk;
207 }
208
209 // ============================================================================
210 //  Function: findGroup
211 //  Purpose:  search groups of entities interacting with given feature
212 // ============================================================================
213 SketchGroupPtr SketchSolver_Manager::findGroup(
214     std::shared_ptr<SketchPlugin_Feature> theFeature)
215 {
216   if (!isFeatureValid(theFeature))
217     return SketchGroupPtr(); // do not process wrong features
218
219   // Obtain sketch, containing the feature
220   CompositeFeaturePtr aSketch;
221   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
222   std::set<AttributePtr>::const_iterator aRefIt = aRefsList.begin();
223   for (; aRefIt != aRefsList.end(); ++aRefIt) {
224     FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
225     if (anOwner && anOwner->getKind() == SketchPlugin_Sketch::ID()) {
226       aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(anOwner);
227       break;
228     }
229   }
230
231   if (!aSketch)
232     return SketchGroupPtr(); // not a sketch's feature
233
234   std::list<SketchGroupPtr>::const_iterator aGroupIt;
235   for (aGroupIt = myGroups.begin(); aGroupIt != myGroups.end(); ++aGroupIt)
236     if ((*aGroupIt)->getWorkplane() == aSketch)
237       return *aGroupIt;
238
239   // group for the sketch does not created yet
240   SketchGroupPtr aNewGroup = SketchGroupPtr(new SketchSolver_Group(aSketch));
241   myGroups.push_back(aNewGroup);
242   return aNewGroup;
243 }
244
245 // ============================================================================
246 //  Function: resolveConstraints
247 //  Purpose:  change entities according to available constraints
248 // ============================================================================
249 bool SketchSolver_Manager::resolveConstraints()
250 {
251   bool needToUpdate = false;
252   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
253   for (; aGroupIter != myGroups.end(); ++aGroupIter) {
254     if ((*aGroupIter)->resolveConstraints())
255       needToUpdate = true;
256   }
257   return needToUpdate;
258 }
259
260 void SketchSolver_Manager::releaseFeaturesIfEventsBlocked() const
261 {
262   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
263   for (; aGroupIter != myGroups.end(); ++aGroupIter)
264     (*aGroupIter)->blockEvents(false);
265 }
266
267 bool SketchSolver_Manager::stopSendUpdate() const
268 {
269 static const Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
270   // to avoid redisplay of each segment on update by solver one by one in the viewer
271   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
272   if (isUpdateFlushed) {
273     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
274   }
275   return isUpdateFlushed;
276 }
277
278 void SketchSolver_Manager::allowSendUpdate() const
279 {
280   Events_Loop::loop()->setFlushed(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), true);
281 }