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_Arc.h>
23 #include <SketchPlugin_ConstraintAngle.h>
24 #include <SketchPlugin_ConstraintCoincidence.h>
25 #include <SketchPlugin_ConstraintDistance.h>
26 #include <SketchPlugin_ConstraintEqual.h>
27 #include <SketchPlugin_ConstraintHorizontal.h>
28 #include <SketchPlugin_ConstraintLength.h>
29 #include <SketchPlugin_ConstraintFillet.h>
30 #include <SketchPlugin_ConstraintMirror.h>
31 #include <SketchPlugin_ConstraintParallel.h>
32 #include <SketchPlugin_ConstraintPerpendicular.h>
33 #include <SketchPlugin_ConstraintRadius.h>
34 #include <SketchPlugin_ConstraintRigid.h>
35 #include <SketchPlugin_ConstraintTangent.h>
36 #include <SketchPlugin_ConstraintVertical.h>
37 #include <SketchPlugin_MultiRotation.h>
38 #include <SketchPlugin_MultiTranslation.h>
44 /// \brief This class is used to give unique index to the groups
48 /// \brief Return vacant index
49 static GroupID NEW_GROUP() { return ++myGroupIndex; }
50 /// \brief Removes the index
51 static void REMOVE_GROUP(const GroupID& theIndex) {
52 if (myGroupIndex == theIndex)
59 static GroupID myGroupIndex; ///< index of the group
62 GroupID GroupIndexer::myGroupIndex = GID_OUTOFGROUP;
65 static void sendMessage(const char* theMessageName)
67 std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
68 new Events_Message(Events_Loop::eventByName(theMessageName)));
69 Events_Loop::loop()->send(aMessage);
72 static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& theConflicting)
74 std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
75 std::shared_ptr<ModelAPI_SolverFailedMessage>(
76 new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
77 aMessage->setObjects(theConflicting);
78 Events_Loop::loop()->send(aMessage);
83 // ========================================================
84 // ========= SketchSolver_Group ===============
85 // ========================================================
87 SketchSolver_Group::SketchSolver_Group(
88 std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
89 : myID(GroupIndexer::NEW_GROUP()),
90 myPrevResult(STATUS_UNKNOWN)
92 // Initialize workplane
93 myWorkplaneID = EID_UNKNOWN;
94 addWorkplane(theWorkplane);
97 SketchSolver_Group::~SketchSolver_Group()
99 myConstraints.clear();
100 GroupIndexer::REMOVE_GROUP(myID);
103 // ============================================================================
104 // Function: isBaseWorkplane
105 // Class: SketchSolver_Group
106 // Purpose: verify the group is based on the given workplane
107 // ============================================================================
108 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
110 return theWorkplane == mySketch;
113 // ============================================================================
114 // Function: isInteract
115 // Class: SketchSolver_Group
116 // Purpose: verify are there any entities in the group used by given constraint
117 // ============================================================================
118 bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
120 // Empty group interacts with everything
123 // Check interaction with the storage
124 return myStorage->isInteract(theFeature);
127 // ============================================================================
128 // Function: changeConstraint
129 // Class: SketchSolver_Group
130 // Purpose: create/update the constraint in the group
131 // ============================================================================
132 bool SketchSolver_Group::changeConstraint(
133 std::shared_ptr<SketchPlugin_Constraint> theConstraint)
135 // There is no workplane yet, something wrong
136 if (myWorkplaneID == EID_UNKNOWN)
139 if (!theConstraint || !theConstraint->data())
142 if (!checkFeatureValidity(theConstraint))
145 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
146 myStorage->blockEvents(true);
148 bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
149 if (isNewConstraint) {
150 // Add constraint to the current group
151 SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
154 aConstraint->process(myStorage, getId(), getWorkplaneId());
155 if (!aConstraint->error().empty()) {
156 if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
157 return false; // some attribute are not initialized yet, don't show message
158 Events_Error::send(aConstraint->error(), this);
160 myConstraints[theConstraint] = aConstraint;
163 myConstraints[theConstraint]->update();
166 if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
167 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
168 theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
169 if (aRefAttr && aRefAttr->isObject()) {
170 std::shared_ptr<SketchPlugin_Feature> aFeature =
171 std::dynamic_pointer_cast<SketchPlugin_Feature>(
172 ModelAPI_Feature::feature(aRefAttr->object()));
174 SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
176 aConstraint->process(myStorage, getId(), getWorkplaneId());
177 setTemporary(aConstraint);
185 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
187 ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
188 for (; aCIt != theConstraints.end(); ++aCIt) {
189 if ((aCIt->second->getType() == CONSTRAINT_MULTI_ROTATION ||
190 aCIt->second->getType() == CONSTRAINT_MULTI_TRANSLATION)
191 && aCIt->second->isUsed(theFeature))
192 std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
193 else if (aCIt->second->getType() == CONSTRAINT_TANGENT_CIRCLE_LINE
194 && aCIt->second->isUsed(theFeature))
195 aCIt->second->update();
199 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
201 if (!checkFeatureValidity(theFeature))
204 bool isBlocked = myStorage->isEventsBlocked();
206 myStorage->blockEvents(true);
208 myStorage->refresh(true);
209 bool isUpdated = myStorage->update(theFeature);
211 updateMultiConstraints(myConstraints, theFeature);
213 // events were not blocked before, the feature has not been updated,
214 // so it is necessary to revert blocking
215 if (!isUpdated && !isBlocked)
216 myStorage->blockEvents(false);
220 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
222 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
224 // Firstly, revert changes in the fixed entities
225 myStorage->blockEvents(true);
226 myStorage->refresh(true);
228 // Then, create temporary Fixed constraint
229 SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
232 aConstraint->process(myStorage, getId(), getWorkplaneId());
233 if (aConstraint->error().empty())
234 setTemporary(aConstraint);
236 // Secondly, search attributes of the feature in the list of the Multi constraints and update them
237 updateMultiConstraints(myConstraints, theFeature);
239 // Workaround to process arcs.
240 // When move unconstrained arc, add temporary constraint to fix radius.
241 if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
242 SolverConstraintPtr aFixedRadius = aBuilder->createFixedArcRadiusConstraint(theFeature);
244 aFixedRadius->process(myStorage, getId(), getWorkplaneId());
245 if (aFixedRadius->error().empty())
246 setTemporary(aFixedRadius);
251 // ============================================================================
252 // Function: addWorkplane
253 // Class: SketchSolver_Group
254 // Purpose: create workplane for the group
255 // ============================================================================
256 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
258 if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
259 return false; // the workplane already exists or the function parameter is not Sketch
261 mySketch = theSketch;
262 if (!updateWorkplane()) {
263 mySketch = CompositeFeaturePtr();
269 // ============================================================================
270 // Function: updateWorkplane
271 // Class: SketchSolver_Group
272 // Purpose: update parameters of workplane
273 // ============================================================================
274 bool SketchSolver_Group::updateWorkplane()
276 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
277 if (!myStorage) // Create storage if not exists
278 myStorage = aBuilder->createStorage(getId());
280 // sketch should be unchanged, set it out of current group
281 bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
283 EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
284 myWorkplaneID = anEntity->id();
289 // ============================================================================
290 // Function: resolveConstraints
291 // Class: SketchSolver_Group
292 // Purpose: solve the set of constraints for the current group
293 // ============================================================================
294 bool SketchSolver_Group::resolveConstraints()
296 bool aResolved = false;
297 bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
298 if (myStorage->isNeedToResolve() && !isGroupEmpty) {
300 mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
302 mySketchSolver->setGroup(myID);
303 mySketchSolver->calculateFailedConstraints(false);
304 myStorage->initializeSolver(mySketchSolver);
305 mySketchSolver->prepare();
307 SketchSolver_SolveStatus aResult = STATUS_OK;
309 if (myStorage->hasDuplicatedConstraint())
310 aResult = STATUS_INCONSISTENT;
312 // To avoid overconstraint situation, we will remove temporary constraints one-by-one
313 // and try to find the case without overconstraint
314 bool isLastChance = false;
316 aResult = mySketchSolver->solve();
317 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
319 //// // try to update parameters and resolve once again
320 //// ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
321 //// for (; aConstrIt != myConstraints.end(); ++aConstrIt)
322 //// aConstrIt->second->update();
325 removeTemporaryConstraints();
326 mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
327 myStorage->initializeSolver(mySketchSolver);
331 // Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
332 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
333 if (myPrevResult == STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
334 // the error message should be changed before sending the message
335 sendMessage(EVENT_SOLVER_FAILED);
336 myPrevResult = STATUS_FAILED;
338 mySketchSolver->undo();
341 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) { // solution succeeded, store results into correspondent attributes
342 myStorage->refresh();
343 if (myPrevResult != STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
344 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
345 // the error message should be changed before sending the message
346 sendMessage(EVENT_SOLVER_REPAIRED);
347 myPrevResult = STATUS_OK;
350 mySketchSolver->undo();
351 if (!myConstraints.empty()) {
352 // Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
353 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
354 if (myPrevResult != aResult || myPrevResult == STATUS_UNKNOWN) {
355 // Obtain list of conflicting constraints
356 std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
358 // the error message should be changed before sending the message
359 sendMessage(EVENT_SOLVER_FAILED, aConflicting);
360 myPrevResult = aResult;
366 } else if (!isGroupEmpty) {
367 // Check there are constraints Fixed. If they exist, update parameters by stored values
368 ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
369 for (; aCIt != myConstraints.end(); ++aCIt)
370 if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
374 if (aCIt != myConstraints.end())
375 myStorage->refresh();
377 removeTemporaryConstraints();
378 myStorage->blockEvents(false);
379 myStorage->setNeedToResolve(false);
383 // ============================================================================
384 // Function: mergeGroups
385 // Class: SketchSolver_Group
386 // Purpose: append specified group to the current group
387 // ============================================================================
388 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
390 // If specified group is empty, no need to merge
391 if (theGroup.isEmpty())
394 std::set<ObjectPtr> aConstraints;
395 ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
396 for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
397 aConstraints.insert(aConstrIter->first);
399 std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
400 std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
401 for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
402 ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
405 changeConstraint(aConstr);
409 // ============================================================================
410 // Function: splitGroup
411 // Class: SketchSolver_Group
412 // Purpose: divide the group into several subgroups
413 // ============================================================================
414 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
416 // New storage will be used in trimmed way to store the list of constraint interacted together.
417 StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
418 std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
420 // Obtain constraints, which should be separated
421 std::list<ConstraintPtr> anUnusedConstraints;
422 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
423 for ( ; aCIter != myConstraints.end(); aCIter++) {
424 if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
425 aNewStorage->addConstraint(aCIter->first, aDummyVec);
427 anUnusedConstraints.push_back(aCIter->first);
430 // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
431 std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
432 while (aUnuseIt != anUnusedConstraints.end()) {
433 if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
434 aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
435 anUnusedConstraints.erase(aUnuseIt);
436 aUnuseIt = anUnusedConstraints.begin();
442 std::list<SketchSolver_Group*>::iterator aCutsIter;
443 aUnuseIt = anUnusedConstraints.begin();
444 for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
445 // Remove unused constraints
446 removeConstraint(*aUnuseIt);
447 // Try to append constraint to already existent group
448 for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
449 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
450 (*aCutsIter)->changeConstraint(*aUnuseIt);
453 if (aCutsIter == theCuts.end()) {
455 SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
456 aGroup->changeConstraint(*aUnuseIt);
457 theCuts.push_back(aGroup);
459 // Find other groups interacting with constraint
460 std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
461 for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
462 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
463 (*aBaseGroupIt)->mergeGroups(**aCutsIter);
464 std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
465 theCuts.erase(aRemoveIt);
471 // ============================================================================
472 // Function: isConsistent
473 // Class: SketchSolver_Group
474 // Purpose: search removed entities and constraints
475 // ============================================================================
476 bool SketchSolver_Group::isConsistent()
478 if (isEmpty()) // no one constraint is initialized yet
481 // Check the features and constraint is the storage are valid
482 bool aResult = myStorage->isConsistent();
484 // additional check of consistency of the Fixed constraint,
485 // because they are not added to the storage
486 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
487 for (; aCIter != myConstraints.end(); ++aCIter)
488 if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
489 (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
495 // remove invalid constraints
496 std::set<ConstraintPtr> anInvalidConstraints;
497 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
498 for (; aCIter != myConstraints.end(); ++aCIter) {
499 if (!aCIter->first->data() || !aCIter->first->data()->isValid())
500 anInvalidConstraints.insert(aCIter->first);
502 std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
503 for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
504 removeConstraint(*aRemoveIt);
505 // remove invalid features
506 myStorage->removeInvalidEntities();
511 // ============================================================================
512 // Function: removeTemporaryConstraints
513 // Class: SketchSolver_Group
514 // Purpose: remove all transient SLVS_C_WHERE_DRAGGED constraints after
515 // resolving the set of constraints
516 // ============================================================================
517 void SketchSolver_Group::removeTemporaryConstraints()
519 std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
520 for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
523 if (!myTempConstraints.empty())
524 myStorage->verifyFixed();
525 myStorage->setNeedToResolve(false);
526 myTempConstraints.clear();
529 // ============================================================================
530 // Function: removeConstraint
531 // Class: SketchSolver_Group
532 // Purpose: remove constraint and all unused entities
533 // ============================================================================
534 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
536 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
537 for (; aCIter != myConstraints.end(); aCIter++)
538 if (aCIter->first == theConstraint) {
539 aCIter->second->remove(); // the constraint is not fully removed
542 if (aCIter != myConstraints.end())
543 myConstraints.erase(aCIter);
546 // ============================================================================
547 // Function: setTemporary
548 // Class: SketchSolver_Group
549 // Purpose: append given constraint to the group of temporary constraints
550 // ============================================================================
551 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
553 myTempConstraints.insert(theConstraint);
557 // ============================================================================
558 // Function: checkFeatureValidity
559 // Class: SketchSolver_Group
560 // Purpose: verifies is the feature valid
561 // ============================================================================
562 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
564 if (!theFeature || !theFeature->data()->isValid())
567 SessionPtr aMgr = ModelAPI_Session::get();
568 ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
569 return aFactory->validate(theFeature);
575 // =========== Auxiliary functions ========================================
576 static double featureToVal(FeaturePtr theFeature)
578 if (theFeature->getKind() == SketchPlugin_Sketch::ID())
579 return 0.0; // sketch
580 ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
582 return 1.0; // features (arc, circle, line, point)
584 const std::string& anID = aConstraint->getKind();
585 if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
586 AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
587 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
588 AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
589 aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
590 if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
591 return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
594 if (anID == SketchPlugin_ConstraintDistance::ID() ||
595 anID == SketchPlugin_ConstraintLength::ID() ||
596 anID == SketchPlugin_ConstraintRadius::ID())
598 if (anID == SketchPlugin_ConstraintAngle::ID())
600 if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
601 anID == SketchPlugin_ConstraintVertical::ID() ||
602 anID == SketchPlugin_ConstraintParallel::ID() ||
603 anID == SketchPlugin_ConstraintPerpendicular::ID())
605 if (anID == SketchPlugin_ConstraintEqual::ID())
607 if (anID == SketchPlugin_ConstraintTangent::ID() ||
608 anID == SketchPlugin_ConstraintMirror::ID())
610 if (anID == SketchPlugin_ConstraintRigid::ID())
612 if (anID == SketchPlugin_MultiRotation::ID() ||
613 anID == SketchPlugin_MultiTranslation::ID())
616 // all other constraints are placed between Equal and Tangent constraints
620 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
622 return featureToVal(theFeature1) < featureToVal(theFeature2);
625 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
627 std::list<FeaturePtr> aResult;
628 std::list<FeaturePtr>::iterator aResIt;
630 std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
631 for (; anObjIter != theObjects.end(); ++anObjIter) {
632 // Operate sketch itself and SketchPlugin features only.
633 // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
634 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
637 std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
638 std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
639 if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
640 aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
643 // Find the place where to insert a feature
644 for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
645 if (isLess(aFeature, *aResIt))
647 aResult.insert(aResIt, aFeature);