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