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);
74 // ========================================================
75 // ========= SketchSolver_Group ===============
76 // ========================================================
78 SketchSolver_Group::SketchSolver_Group(
79 std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
80 : myID(GroupIndexer::NEW_GROUP()),
81 myPrevResult(STATUS_UNKNOWN)
83 // Initialize workplane
84 myWorkplaneID = EID_UNKNOWN;
85 addWorkplane(theWorkplane);
88 SketchSolver_Group::~SketchSolver_Group()
90 myConstraints.clear();
91 GroupIndexer::REMOVE_GROUP(myID);
94 // ============================================================================
95 // Function: isBaseWorkplane
96 // Class: SketchSolver_Group
97 // Purpose: verify the group is based on the given workplane
98 // ============================================================================
99 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
101 return theWorkplane == mySketch;
104 // ============================================================================
105 // Function: isInteract
106 // Class: SketchSolver_Group
107 // Purpose: verify are there any entities in the group used by given constraint
108 // ============================================================================
109 bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
111 // Empty group interacts with everything
114 // Check interaction with the storage
115 return myStorage->isInteract(theFeature);
118 // ============================================================================
119 // Function: changeConstraint
120 // Class: SketchSolver_Group
121 // Purpose: create/update the constraint in the group
122 // ============================================================================
123 bool SketchSolver_Group::changeConstraint(
124 std::shared_ptr<SketchPlugin_Constraint> theConstraint)
126 // There is no workplane yet, something wrong
127 if (myWorkplaneID == EID_UNKNOWN)
130 if (!theConstraint || !theConstraint->data())
133 if (!checkFeatureValidity(theConstraint))
136 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
137 myStorage->blockEvents(true);
139 bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
140 if (isNewConstraint) {
141 // Add constraint to the current group
142 SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
145 aConstraint->process(myStorage, getId(), getWorkplaneId());
146 if (!aConstraint->error().empty()) {
147 if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
148 return false; // some attribute are not initialized yet, don't show message
149 Events_Error::send(aConstraint->error(), this);
151 myConstraints[theConstraint] = aConstraint;
154 myConstraints[theConstraint]->update();
157 if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
158 AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
159 theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
160 if (aRefAttr && aRefAttr->isObject()) {
161 std::shared_ptr<SketchPlugin_Feature> aFeature =
162 std::dynamic_pointer_cast<SketchPlugin_Feature>(
163 ModelAPI_Feature::feature(aRefAttr->object()));
165 SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
167 aConstraint->process(myStorage, getId(), getWorkplaneId());
168 setTemporary(aConstraint);
176 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
178 ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
179 for (; aCIt != theConstraints.end(); ++aCIt) {
180 if ((aCIt->second->getType() == CONSTRAINT_MULTI_ROTATION ||
181 aCIt->second->getType() == CONSTRAINT_MULTI_TRANSLATION)
182 && aCIt->second->isUsed(theFeature))
183 std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
187 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
189 if (!checkFeatureValidity(theFeature))
192 bool isBlocked = myStorage->isEventsBlocked();
194 myStorage->blockEvents(true);
196 myStorage->refresh(true);
197 bool isUpdated = myStorage->update(theFeature);
199 updateMultiConstraints(myConstraints, theFeature);
201 // events were not blocked before, the feature has not been updated,
202 // so it is necessary to revert blocking
203 if (!isUpdated && !isBlocked)
204 myStorage->blockEvents(false);
208 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
210 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
212 // Firstly, revert changes in the fixed entities
213 myStorage->blockEvents(true);
214 myStorage->refresh(true);
216 // Then, create temporary Fixed constraint
217 SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
220 aConstraint->process(myStorage, getId(), getWorkplaneId());
221 if (aConstraint->error().empty())
222 setTemporary(aConstraint);
224 // Secondly, search attributes of the feature in the list of the Multi constraints and update them
225 updateMultiConstraints(myConstraints, theFeature);
227 // Workaround to process arcs.
228 // When move unconstrained arc, add temporary constraint to fix radius.
229 if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
230 SolverConstraintPtr aFixedRadius = aBuilder->createFixedArcRadiusConstraint(theFeature);
232 aFixedRadius->process(myStorage, getId(), getWorkplaneId());
233 if (aFixedRadius->error().empty())
234 setTemporary(aFixedRadius);
239 // ============================================================================
240 // Function: addWorkplane
241 // Class: SketchSolver_Group
242 // Purpose: create workplane for the group
243 // ============================================================================
244 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
246 if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
247 return false; // the workplane already exists or the function parameter is not Sketch
249 mySketch = theSketch;
250 if (!updateWorkplane()) {
251 mySketch = CompositeFeaturePtr();
257 // ============================================================================
258 // Function: updateWorkplane
259 // Class: SketchSolver_Group
260 // Purpose: update parameters of workplane
261 // ============================================================================
262 bool SketchSolver_Group::updateWorkplane()
264 BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
265 if (!myStorage) // Create storage if not exists
266 myStorage = aBuilder->createStorage(getId());
268 // sketch should be unchanged, set it out of current group
269 bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
271 EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
272 myWorkplaneID = anEntity->id();
277 // ============================================================================
278 // Function: resolveConstraints
279 // Class: SketchSolver_Group
280 // Purpose: solve the set of constraints for the current group
281 // ============================================================================
282 bool SketchSolver_Group::resolveConstraints()
284 bool aResolved = false;
285 bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
286 if (myStorage->isNeedToResolve() && !isGroupEmpty) {
288 mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
290 mySketchSolver->setGroup(myID);
291 mySketchSolver->calculateFailedConstraints(false);
292 myStorage->initializeSolver(mySketchSolver);
293 mySketchSolver->prepare();
295 SketchSolver_SolveStatus aResult = STATUS_OK;
297 if (myStorage->hasDuplicatedConstraint())
298 aResult = STATUS_INCONSISTENT;
300 // To avoid overconstraint situation, we will remove temporary constraints one-by-one
301 // and try to find the case without overconstraint
302 bool isLastChance = false;
304 aResult = mySketchSolver->solve();
305 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
307 // try to update parameters and resolve once again
308 ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
309 for (; aConstrIt != myConstraints.end(); ++aConstrIt)
310 aConstrIt->second->update();
313 removeTemporaryConstraints();
314 mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
315 myStorage->initializeSolver(mySketchSolver);
319 // Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
320 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
321 if (myPrevResult == STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
322 // the error message should be changed before sending the message
323 sendMessage(EVENT_SOLVER_FAILED);
324 myPrevResult = STATUS_FAILED;
326 mySketchSolver->undo();
329 if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) { // solution succeeded, store results into correspondent attributes
330 myStorage->refresh();
331 if (myPrevResult != STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
332 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
333 // the error message should be changed before sending the message
334 sendMessage(EVENT_SOLVER_REPAIRED);
335 myPrevResult = STATUS_OK;
338 mySketchSolver->undo();
339 if (!myConstraints.empty()) {
340 // Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
341 getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
342 if (myPrevResult != aResult || myPrevResult == STATUS_UNKNOWN) {
343 // the error message should be changed before sending the message
344 sendMessage(EVENT_SOLVER_FAILED);
345 myPrevResult = aResult;
351 } else if (!isGroupEmpty) {
352 // Check there are constraints Fixed. If they exist, update parameters by stored values
353 ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
354 for (; aCIt != myConstraints.end(); ++aCIt)
355 if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
359 if (aCIt != myConstraints.end())
360 myStorage->refresh();
362 removeTemporaryConstraints();
363 myStorage->blockEvents(false);
364 myStorage->setNeedToResolve(false);
368 // ============================================================================
369 // Function: mergeGroups
370 // Class: SketchSolver_Group
371 // Purpose: append specified group to the current group
372 // ============================================================================
373 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
375 // If specified group is empty, no need to merge
376 if (theGroup.isEmpty())
379 std::set<ObjectPtr> aConstraints;
380 ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
381 for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
382 aConstraints.insert(aConstrIter->first);
384 std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
385 std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
386 for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
387 ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
390 changeConstraint(aConstr);
394 // ============================================================================
395 // Function: splitGroup
396 // Class: SketchSolver_Group
397 // Purpose: divide the group into several subgroups
398 // ============================================================================
399 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
401 // New storage will be used in trimmed way to store the list of constraint interacted together.
402 StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
403 std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
405 // Obtain constraints, which should be separated
406 std::list<ConstraintPtr> anUnusedConstraints;
407 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
408 for ( ; aCIter != myConstraints.end(); aCIter++) {
409 if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
410 aNewStorage->addConstraint(aCIter->first, aDummyVec);
412 anUnusedConstraints.push_back(aCIter->first);
415 // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
416 std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
417 while (aUnuseIt != anUnusedConstraints.end()) {
418 if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
419 aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
420 anUnusedConstraints.erase(aUnuseIt);
421 aUnuseIt = anUnusedConstraints.begin();
427 std::list<SketchSolver_Group*>::iterator aCutsIter;
428 aUnuseIt = anUnusedConstraints.begin();
429 for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
430 // Remove unused constraints
431 removeConstraint(*aUnuseIt);
432 // Try to append constraint to already existent group
433 for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
434 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
435 (*aCutsIter)->changeConstraint(*aUnuseIt);
438 if (aCutsIter == theCuts.end()) {
440 SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
441 aGroup->changeConstraint(*aUnuseIt);
442 theCuts.push_back(aGroup);
444 // Find other groups interacting with constraint
445 std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
446 for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
447 if ((*aCutsIter)->isInteract(*aUnuseIt)) {
448 (*aBaseGroupIt)->mergeGroups(**aCutsIter);
449 std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
450 theCuts.erase(aRemoveIt);
456 // ============================================================================
457 // Function: isConsistent
458 // Class: SketchSolver_Group
459 // Purpose: search removed entities and constraints
460 // ============================================================================
461 bool SketchSolver_Group::isConsistent()
463 if (isEmpty()) // no one constraint is initialized yet
466 // Check the features and constraint is the storage are valid
467 bool aResult = myStorage->isConsistent();
469 // additional check of consistency of the Fixed constraint,
470 // because they are not added to the storage
471 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
472 for (; aCIter != myConstraints.end(); ++aCIter)
473 if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
474 (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
480 // remove invalid constraints
481 std::set<ConstraintPtr> anInvalidConstraints;
482 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
483 for (; aCIter != myConstraints.end(); ++aCIter) {
484 if (!aCIter->first->data() || !aCIter->first->data()->isValid())
485 anInvalidConstraints.insert(aCIter->first);
487 std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
488 for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
489 removeConstraint(*aRemoveIt);
490 // remove invalid features
491 myStorage->removeInvalidEntities();
496 // ============================================================================
497 // Function: removeTemporaryConstraints
498 // Class: SketchSolver_Group
499 // Purpose: remove all transient SLVS_C_WHERE_DRAGGED constraints after
500 // resolving the set of constraints
501 // ============================================================================
502 void SketchSolver_Group::removeTemporaryConstraints()
504 std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
505 for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
508 if (!myTempConstraints.empty())
509 myStorage->verifyFixed();
510 myStorage->setNeedToResolve(false);
511 myTempConstraints.clear();
514 // ============================================================================
515 // Function: removeConstraint
516 // Class: SketchSolver_Group
517 // Purpose: remove constraint and all unused entities
518 // ============================================================================
519 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
521 ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
522 for (; aCIter != myConstraints.end(); aCIter++)
523 if (aCIter->first == theConstraint) {
524 aCIter->second->remove(); // the constraint is not fully removed
527 if (aCIter != myConstraints.end())
528 myConstraints.erase(aCIter);
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);