1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: SketchSolver_Group.cpp
4 // Created: 27 May 2014
5 // Author: Artem ZHIDKOV
7 #include "SketchSolver_Group.h"
9 #include <SketchSolver_Constraint.h>
10 #include <SketchSolver_ConstraintCoincidence.h>
11 #include <SketchSolver_ConstraintMulti.h>
12 #include <SketchSolver_Error.h>
13 #include <SketchSolver_Manager.h>
15 #include <Events_Error.h>
16 #include <Events_Loop.h>
17 #include <ModelAPI_AttributeString.h>
18 #include <ModelAPI_Events.h>
19 #include <ModelAPI_Session.h>
20 #include <ModelAPI_Validator.h>
22 #include <SketchPlugin_ConstraintAngle.h>
23 #include <SketchPlugin_ConstraintCoincidence.h>
24 #include <SketchPlugin_ConstraintDistance.h>
25 #include <SketchPlugin_ConstraintEqual.h>
26 #include <SketchPlugin_ConstraintHorizontal.h>
27 #include <SketchPlugin_ConstraintLength.h>
28 #include <SketchPlugin_ConstraintFillet.h>
29 #include <SketchPlugin_ConstraintMirror.h>
30 #include <SketchPlugin_ConstraintParallel.h>
31 #include <SketchPlugin_ConstraintPerpendicular.h>
32 #include <SketchPlugin_ConstraintRadius.h>
33 #include <SketchPlugin_ConstraintRigid.h>
34 #include <SketchPlugin_ConstraintTangent.h>
35 #include <SketchPlugin_ConstraintVertical.h>
36 #include <SketchPlugin_MultiRotation.h>
37 #include <SketchPlugin_MultiTranslation.h>
43 /// \brief This class is used to give unique index to the groups
47 /// \brief Return vacant index
48 static GroupID NEW_GROUP() { return ++myGroupIndex; }
49 /// \brief Removes the index
50 static void REMOVE_GROUP(const GroupID& theIndex) {
51 if (myGroupIndex == theIndex)
58 static GroupID myGroupIndex; ///< index of the group
61 GroupID GroupIndexer::myGroupIndex = GID_OUTOFGROUP;
64 static void sendMessage(const char* theMessageName)
66 std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
67 new Events_Message(Events_Loop::eventByName(theMessageName)));
68 Events_Loop::loop()->send(aMessage);
73 // ========================================================
74 // ========= SketchSolver_Group ===============
75 // ========================================================
77 SketchSolver_Group::SketchSolver_Group(
78 std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
79 : myID(GroupIndexer::NEW_GROUP()),
80 myPrevResult(STATUS_UNKNOWN)
82 // Initialize workplane
83 myWorkplaneID = EID_UNKNOWN;
84 addWorkplane(theWorkplane);
87 SketchSolver_Group::~SketchSolver_Group()
89 myConstraints.clear();
90 GroupIndexer::REMOVE_GROUP(myID);
93 // ============================================================================
94 // Function: isBaseWorkplane
95 // Class: SketchSolver_Group
96 // Purpose: verify the group is based on the given workplane
97 // ============================================================================
98 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
100 return theWorkplane == mySketch;
103 // ============================================================================
104 // Function: isInteract
105 // Class: SketchSolver_Group
106 // Purpose: verify are there any entities in the group used by given constraint
107 // ============================================================================
108 bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
110 // Empty group interacts with everything
113 // Check interaction with the storage
114 return myStorage->isInteract(theFeature);
117 // ============================================================================
118 // Function: changeConstraint
119 // Class: SketchSolver_Group
120 // Purpose: create/update the constraint in the group
121 // ============================================================================
122 bool SketchSolver_Group::changeConstraint(
123 std::shared_ptr<SketchPlugin_Constraint> theConstraint)
125 // There is no workplane yet, something wrong
126 if (myWorkplaneID == EID_UNKNOWN)
129 if (!theConstraint || !theConstraint->data())
132 if (!checkFeatureValidity(theConstraint))
135 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
136 myStorage->blockEvents(true);
138 bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
139 if (isNewConstraint) {
140 // Add constraint to the current group
141 SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
144 aConstraint->process(myStorage, getId(), getWorkplaneId());
145 if (!aConstraint->error().empty()) {
146 if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
147 return false; // some attribute are not initialized yet, don't show message
148 Events_Error::send(aConstraint->error(), this);
150 myConstraints[theConstraint] = aConstraint;
153 myConstraints[theConstraint]->update();
156 if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
157 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
158 theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
159 if (aRefAttr && aRefAttr->isObject()) {
160 std::shared_ptr<SketchPlugin_Feature> aFeature =
161 std::dynamic_pointer_cast<SketchPlugin_Feature>(
162 ModelAPI_Feature::feature(aRefAttr->object()));
164 SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
166 aConstraint->process(myStorage, getId(), getWorkplaneId());
167 setTemporary(aConstraint);
175 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
177 ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
178 for (; aCIt != theConstraints.end(); ++aCIt) {
179 if ((aCIt->second->getType() == CONSTRAINT_MULTI_ROTATION ||
180 aCIt->second->getType() == CONSTRAINT_MULTI_TRANSLATION)
181 && aCIt->second->isUsed(theFeature))
182 std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
186 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
188 if (!checkFeatureValidity(theFeature))
191 bool isBlocked = myStorage->isEventsBlocked();
193 myStorage->blockEvents(true);
195 myStorage->refresh(true);
196 bool isUpdated = myStorage->update(theFeature);
198 updateMultiConstraints(myConstraints, theFeature);
200 // events were not blocked before, the feature has not been updated,
201 // so it is necessary to revert blocking
202 if (!isUpdated && !isBlocked)
203 myStorage->blockEvents(false);
207 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
209 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
211 // Firstly, revert changes in the fixed entities
212 myStorage->blockEvents(true);
213 myStorage->refresh(true);
215 // Then, create temporary Fixed constraint
216 SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
219 aConstraint->process(myStorage, getId(), getWorkplaneId());
220 if (aConstraint->error().empty())
221 setTemporary(aConstraint);
223 // Secondly, search attributes of the feature in the list of the Multi constraints and update them
224 updateMultiConstraints(myConstraints, theFeature);
227 // ============================================================================
228 // Function: addWorkplane
229 // Class: SketchSolver_Group
230 // Purpose: create workplane for the group
231 // ============================================================================
232 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
234 if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
235 return false; // the workplane already exists or the function parameter is not Sketch
237 mySketch = theSketch;
238 if (!updateWorkplane()) {
239 mySketch = CompositeFeaturePtr();
245 // ============================================================================
246 // Function: updateWorkplane
247 // Class: SketchSolver_Group
248 // Purpose: update parameters of workplane
249 // ============================================================================
250 bool SketchSolver_Group::updateWorkplane()
252 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
253 if (!myStorage) // Create storage if not exists
254 myStorage = aBuilder->createStorage(getId());
256 // sketch should be unchanged, set it out of current group
257 bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
259 EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
260 myWorkplaneID = anEntity->id();
265 // ============================================================================
266 // Function: resolveConstraints
267 // Class: SketchSolver_Group
268 // Purpose: solve the set of constraints for the current group
269 // ============================================================================
270 bool SketchSolver_Group::resolveConstraints()
272 bool aResolved = false;
273 bool isGroupEmpty = isEmpty();
274 if (myStorage->isNeedToResolve() && !isGroupEmpty) {
276 mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
278 mySketchSolver->setGroup(myID);
279 mySketchSolver->calculateFailedConstraints(false);
280 myStorage->initializeSolver(mySketchSolver);
281 mySketchSolver->prepare();
283 SketchSolver_SolveStatus aResult = STATUS_OK;
285 if (myStorage->hasDuplicatedConstraint())
286 aResult = STATUS_INCONSISTENT;
288 // To avoid overconstraint situation, we will remove temporary constraints one-by-one
289 // and try to find the case without overconstraint
290 bool isLastChance = false;
292 aResult = mySketchSolver->solve();
293 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
295 // try to update parameters and resolve once again
296 ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
297 for (; aConstrIt != myConstraints.end(); ++aConstrIt)
298 aConstrIt->second->update();
301 removeTemporaryConstraints();
302 mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
303 myStorage->initializeSolver(mySketchSolver);
307 // Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
308 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
309 if (myPrevResult == STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
310 // the error message should be changed before sending the message
311 sendMessage(EVENT_SOLVER_FAILED);
312 myPrevResult = STATUS_FAILED;
314 mySketchSolver->undo();
317 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) { // solution succeeded, store results into correspondent attributes
318 myStorage->refresh();
319 if (myPrevResult != STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
320 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
321 // the error message should be changed before sending the message
322 sendMessage(EVENT_SOLVER_REPAIRED);
323 myPrevResult = STATUS_OK;
326 mySketchSolver->undo();
327 if (!myConstraints.empty()) {
328 // Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
329 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
330 if (myPrevResult != aResult || myPrevResult == STATUS_UNKNOWN) {
331 // the error message should be changed before sending the message
332 sendMessage(EVENT_SOLVER_FAILED);
333 myPrevResult = aResult;
339 } else if (!isGroupEmpty) {
340 // Check there are constraints Fixed. If they exist, update parameters by stored values
341 ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
342 for (; aCIt != myConstraints.end(); ++aCIt)
343 if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
347 if (aCIt != myConstraints.end())
348 myStorage->refresh();
350 removeTemporaryConstraints();
351 myStorage->blockEvents(false);
352 myStorage->setNeedToResolve(false);
356 // ============================================================================
357 // Function: mergeGroups
358 // Class: SketchSolver_Group
359 // Purpose: append specified group to the current group
360 // ============================================================================
361 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
363 // If specified group is empty, no need to merge
364 if (theGroup.isEmpty())
367 std::set<ObjectPtr> aConstraints;
368 ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
369 for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
370 aConstraints.insert(aConstrIter->first);
372 std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
373 std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
374 for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
375 ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
378 changeConstraint(aConstr);
382 // ============================================================================
383 // Function: splitGroup
384 // Class: SketchSolver_Group
385 // Purpose: divide the group into several subgroups
386 // ============================================================================
387 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
389 // New storage will be used in trimmed way to store the list of constraint interacted together.
390 StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
391 std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
393 // Obtain constraints, which should be separated
394 std::list<ConstraintPtr> anUnusedConstraints;
395 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
396 for ( ; aCIter != myConstraints.end(); aCIter++) {
397 if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
398 aNewStorage->addConstraint(aCIter->first, aDummyVec);
400 anUnusedConstraints.push_back(aCIter->first);
403 // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
404 std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
405 while (aUnuseIt != anUnusedConstraints.end()) {
406 if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
407 aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
408 anUnusedConstraints.erase(aUnuseIt);
409 aUnuseIt = anUnusedConstraints.begin();
415 std::list<SketchSolver_Group*>::iterator aCutsIter;
416 aUnuseIt = anUnusedConstraints.begin();
417 for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
418 // Remove unused constraints
419 removeConstraint(*aUnuseIt);
420 // Try to append constraint to already existent group
421 for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
422 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
423 (*aCutsIter)->changeConstraint(*aUnuseIt);
426 if (aCutsIter == theCuts.end()) {
428 SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
429 aGroup->changeConstraint(*aUnuseIt);
430 theCuts.push_back(aGroup);
432 // Find other groups interacting with constraint
433 std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
434 for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
435 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
436 (*aBaseGroupIt)->mergeGroups(**aCutsIter);
437 std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
438 theCuts.erase(aRemoveIt);
444 // ============================================================================
445 // Function: isConsistent
446 // Class: SketchSolver_Group
447 // Purpose: search removed entities and constraints
448 // ============================================================================
449 bool SketchSolver_Group::isConsistent()
451 if (isEmpty()) // no one constraint is initialized yet
454 // Check the features and constraint is the storage are valid
455 bool aResult = myStorage->isConsistent();
457 // additional check of consistency of the Fixed constraint,
458 // because they are not added to the storage
459 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
460 for (; aCIter != myConstraints.end(); ++aCIter)
461 if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
462 (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
468 // remove invalid constraints
469 std::set<ConstraintPtr> anInvalidConstraints;
470 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
471 for (; aCIter != myConstraints.end(); ++aCIter) {
472 if (!aCIter->first->data() || !aCIter->first->data()->isValid())
473 anInvalidConstraints.insert(aCIter->first);
475 std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
476 for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
477 removeConstraint(*aRemoveIt);
478 // remove invalid features
479 myStorage->removeInvalidEntities();
484 // ============================================================================
485 // Function: removeTemporaryConstraints
486 // Class: SketchSolver_Group
487 // Purpose: remove all transient SLVS_C_WHERE_DRAGGED constraints after
488 // resolving the set of constraints
489 // ============================================================================
490 void SketchSolver_Group::removeTemporaryConstraints()
492 std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
493 for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
496 if (!myTempConstraints.empty())
497 myStorage->verifyFixed();
498 myStorage->setNeedToResolve(false);
499 myTempConstraints.clear();
502 // ============================================================================
503 // Function: removeConstraint
504 // Class: SketchSolver_Group
505 // Purpose: remove constraint and all unused entities
506 // ============================================================================
507 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
509 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
510 for (; aCIter != myConstraints.end(); aCIter++)
511 if (aCIter->first == theConstraint) {
512 aCIter->second->remove(); // the constraint is not fully removed
515 if (aCIter != myConstraints.end())
516 myConstraints.erase(aCIter);
519 // ============================================================================
520 // Function: isComplexConstraint
521 // Class: SketchSolver_Group
522 // Purpose: verifies the constraint is complex, i.e. it needs another constraints to be created before
523 // ============================================================================
524 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
526 return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
527 theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
528 theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
531 // ============================================================================
532 // Function: setTemporary
533 // Class: SketchSolver_Group
534 // Purpose: append given constraint to the group of temporary constraints
535 // ============================================================================
536 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
538 myTempConstraints.insert(theConstraint);
542 // ============================================================================
543 // Function: checkFeatureValidity
544 // Class: SketchSolver_Group
545 // Purpose: verifies is the feature valid
546 // ============================================================================
547 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
549 if (!theFeature || !theFeature->data()->isValid())
552 SessionPtr aMgr = ModelAPI_Session::get();
553 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
554 return aFactory->validate(theFeature);
560 // =========== Auxiliary functions ========================================
561 static double featureToVal(FeaturePtr theFeature)
563 if (theFeature->getKind() == SketchPlugin_Sketch::ID())
564 return 0.0; // sketch
565 ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
567 return 1.0; // features (arc, circle, line, point)
569 const std::string& anID = aConstraint->getKind();
570 if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
571 AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
572 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
573 AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
574 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
575 if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
576 return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
579 if (anID == SketchPlugin_ConstraintDistance::ID() ||
580 anID == SketchPlugin_ConstraintLength::ID() ||
581 anID == SketchPlugin_ConstraintRadius::ID())
583 if (anID == SketchPlugin_ConstraintAngle::ID())
585 if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
586 anID == SketchPlugin_ConstraintVertical::ID() ||
587 anID == SketchPlugin_ConstraintParallel::ID() ||
588 anID == SketchPlugin_ConstraintPerpendicular::ID())
590 if (anID == SketchPlugin_ConstraintEqual::ID())
592 if (anID == SketchPlugin_ConstraintTangent::ID() ||
593 anID == SketchPlugin_ConstraintMirror::ID())
595 if (anID == SketchPlugin_ConstraintRigid::ID())
597 if (anID == SketchPlugin_MultiRotation::ID() ||
598 anID == SketchPlugin_MultiTranslation::ID())
601 // all other constraints are placed between Equal and Tangent constraints
605 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
607 return featureToVal(theFeature1) < featureToVal(theFeature2);
610 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
612 std::list<FeaturePtr> aResult;
613 std::list<FeaturePtr>::iterator aResIt;
615 std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
616 for (; anObjIter != theObjects.end(); ++anObjIter) {
617 // Operate sketch itself and SketchPlugin features only.
618 // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
619 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
622 std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
623 std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
624 if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
625 aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
628 // Find the place where to insert a feature
629 for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
630 if (isLess(aFeature, *aResIt))
632 aResult.insert(aResIt, aFeature);