Salome HOME
357612b549d9c4105d27b1fbcdbea8bd2b341f63
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_MultiRotation.cpp
1 // Copyright (C) 2014-2023  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 "SketchPlugin_MultiRotation.h"
21 #include "SketchPlugin_Tools.h"
22
23 #include <GeomDataAPI_Point2D.h>
24 #include <ModelAPI_AttributeRefAttr.h>
25 #include <ModelAPI_AttributeBoolean.h>
26 #include <ModelAPI_AttributeDouble.h>
27 #include <ModelAPI_AttributeString.h>
28 #include <ModelAPI_AttributeInteger.h>
29 #include <ModelAPI_Data.h>
30 #include <ModelAPI_ResultConstruction.h>
31 #include <ModelAPI_AttributeRefList.h>
32 #include <ModelAPI_Events.h>
33 #include <ModelAPI_Session.h>
34 #include <ModelAPI_Validator.h>
35 #include <ModelAPI_Tools.h>
36
37 #include <SketchPlugin_SketchEntity.h>
38
39 #include <GeomAPI_Pnt2d.h>
40 #include <GeomAPI_XY.h>
41
42 #include <SketcherPrs_Factory.h>
43
44 #include <cmath>
45
46 static const double PI = 3.1415926535897932;
47 static const double PERIOD = 360.0;
48 static const double ANGLETOL = 1.e-7;
49
50 SketchPlugin_MultiRotation::SketchPlugin_MultiRotation()
51   : isUpdatingAngle(false)
52 {
53 }
54
55 void SketchPlugin_MultiRotation::initAttributes()
56 {
57   data()->addAttribute(CENTER_ID(), ModelAPI_AttributeRefAttr::typeId());
58
59   data()->addAttribute(ANGLE_TYPE(),   ModelAPI_AttributeString::typeId());
60   data()->addAttribute(ANGLE_ID(), ModelAPI_AttributeDouble::typeId());
61   data()->addAttribute(NUMBER_OF_OBJECTS_ID(), ModelAPI_AttributeInteger::typeId());
62   data()->addAttribute(SketchPlugin_Constraint::ENTITY_A(), ModelAPI_AttributeRefList::typeId());
63   data()->addAttribute(SketchPlugin_Constraint::ENTITY_B(), ModelAPI_AttributeRefList::typeId());
64   data()->addAttribute(ROTATION_LIST_ID(), ModelAPI_AttributeRefList::typeId());
65   data()->addAttribute(REVERSED_ID(), ModelAPI_AttributeBoolean::typeId());
66
67   ModelAPI_Session::get()->validators()->
68     registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_A());
69   ModelAPI_Session::get()->validators()->
70     registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_B());
71 }
72
73 void SketchPlugin_MultiRotation::execute()
74 {
75   if (!sketch()) {
76     // it is possible, that this method is called before this feature has back reference to sketch
77     // in this case, the execute is performed after this is done
78     return;
79   }
80
81   AttributeRefListPtr aRotationObjectRefs = reflist(ROTATION_LIST_ID());
82   int aNbCopies = integer(NUMBER_OF_OBJECTS_ID())->value() - 1;
83   if (aNbCopies <= 0)
84     return;
85
86   // Obtain center and angle of rotation
87   AttributeRefAttrPtr aCenter = data()->refattr(CENTER_ID());
88   if (!aCenter || !aCenter->isInitialized())
89     return;
90
91   //double anAngle = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
92   //                                                           attribute(ANGLE_ID()))->value();
93
94   // Convert angle to radians
95   //anAngle *= PI / 180.0;
96
97   // Wait all objects being created, then send update events
98   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
99   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
100   if (isUpdateFlushed)
101     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
102
103   // Save the current feature of the document, because new features may appear while executing.
104   // In this case, they will become current. But if the number of copies is updated from outside
105   // of sketch (e.g. by parameter change), the history line should not hold in sketch.
106   keepCurrentFeature();
107
108   std::shared_ptr<ModelAPI_Data> aData = data();
109   AttributeRefListPtr aRefListOfShapes = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
110       aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
111   AttributeRefListPtr aRefListOfRotated = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
112       aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
113   int aCurrentNbCopies = aRefListOfShapes->size() ?
114       aRefListOfRotated->size() / aRefListOfShapes->size() - 1 : 0;
115   std::list<ObjectPtr> anInitialList = aRefListOfShapes->list();
116   std::list<ObjectPtr> aTargetList = aRefListOfRotated->list();
117   std::list<ObjectPtr> anAddition;
118   std::vector<bool> isUsed(anInitialList.size(), false);
119   // collect new items and check the items to remove
120   for(int anInd = 0; anInd < aRotationObjectRefs->size(); anInd++) {
121     ObjectPtr anObject = aRotationObjectRefs->object(anInd);
122     std::list<ObjectPtr>::const_iterator anIt = anInitialList.begin();
123     std::vector<bool>::iterator aUsedIt = isUsed.begin();
124     for (; anIt != anInitialList.end(); anIt++, aUsedIt++)
125       if (*anIt == anObject) {
126         *aUsedIt = true;
127         break;
128       }
129     if (anIt == anInitialList.end())
130       anAddition.push_back(anObject);
131   }
132   // remove unused items
133   std::list<ObjectPtr>::iterator anInitIter = anInitialList.begin();
134   std::list<ObjectPtr>::iterator aTargetIter = aTargetList.begin();
135   std::vector<bool>::iterator aUsedIter = isUsed.begin();
136   std::set<FeaturePtr> aFeaturesToBeRemoved;
137   for (; aUsedIter != isUsed.end(); aUsedIter++) {
138     if (!(*aUsedIter)) {
139       aRefListOfShapes->remove(*anInitIter);
140       aRefListOfRotated->remove(*aTargetIter++);
141       for (int i = 0; i < aCurrentNbCopies && aTargetIter != aTargetList.end();
142            i++, aTargetIter++) {
143         aRefListOfRotated->remove(*aTargetIter);
144         // remove the corresponding feature from the sketch
145         ResultConstructionPtr aRC =
146             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aTargetIter);
147         DocumentPtr aDoc = aRC ? aRC->document() : DocumentPtr();
148         FeaturePtr aFeature =  aDoc ? aDoc->feature(aRC) : FeaturePtr();
149         if (aFeature)
150           aFeaturesToBeRemoved.insert(aFeature);
151       }
152     } else {
153       for (int i = 0; i <= aNbCopies && aTargetIter != aTargetList.end(); i++)
154         aTargetIter++;
155     }
156     if (anInitIter != anInitialList.end())
157       anInitIter++;
158   }
159   ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved);
160   aFeaturesToBeRemoved.clear();
161   // change number of copies
162   if (aCurrentNbCopies != 0 && aNbCopies != aCurrentNbCopies) {
163     bool isAdd = aNbCopies > aCurrentNbCopies;
164     int aMinCopies = isAdd ? aCurrentNbCopies : aNbCopies;
165     int aMaxCopies = isAdd ? aNbCopies : aCurrentNbCopies;
166     int ind = 0;
167
168     aTargetList = aRefListOfRotated->list();
169     aTargetIter = aTargetList.begin();
170     ObjectPtr anObjToCopy = *aTargetIter;
171     while (aTargetIter != aTargetList.end()) {
172       aRefListOfRotated->remove(*aTargetIter);
173       aTargetIter++;
174       ind++;
175       if (ind > aMinCopies && ind <=aMaxCopies) {
176         while (ind <= aMaxCopies) {
177           if (isAdd) {
178             // Add new shifted item
179             ObjectPtr anObject = copyFeature(anObjToCopy);
180             aTargetList.insert(aTargetIter, anObject);
181           } else {
182             // remove object
183             std::list<ObjectPtr>::iterator aRemoveIt = aTargetIter++;
184             ObjectPtr anObject = *aRemoveIt;
185             aTargetList.erase(aRemoveIt);
186             aRefListOfRotated->remove(anObject);
187             // remove the corresponding feature from the sketch
188             ResultConstructionPtr aRC =
189                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anObject);
190             DocumentPtr aDoc = aRC ? aRC->document() : DocumentPtr();
191             FeaturePtr aFeature =  aDoc ? aDoc->feature(aRC) : FeaturePtr();
192             if (aFeature)
193               aFeaturesToBeRemoved.insert(aFeature);
194           }
195           ind++;
196         }
197         ind = 0;
198         if (aTargetIter != aTargetList.end())
199           anObjToCopy = *aTargetIter;
200       }
201     }
202     ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved);
203     aFeaturesToBeRemoved.clear();
204
205     for (aTargetIter = aTargetList.begin(); aTargetIter != aTargetList.end(); aTargetIter++)
206       aRefListOfRotated->append(*aTargetIter);
207   }
208   // add new items
209   std::list<ObjectPtr>::iterator anAddIter = anAddition.begin();
210   for (; anAddIter != anAddition.end(); anAddIter++) {
211     aRefListOfShapes->append(*anAddIter);
212     aRefListOfRotated->append(*anAddIter);
213     for (int i = 0; i < aNbCopies; i++) {
214       ObjectPtr anObject = copyFeature(*anAddIter);
215       aRefListOfRotated->append(anObject);
216     }
217   }
218
219   restoreCurrentFeature();
220
221   // send events to update the sub-features by the solver
222   if (isUpdateFlushed)
223     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
224 }
225
226 AISObjectPtr SketchPlugin_MultiRotation::getAISObject(AISObjectPtr thePrevious)
227 {
228   if (!sketch())
229     return thePrevious;
230
231   AISObjectPtr anAIS = SketcherPrs_Factory::rotateConstraint(this, sketch(),
232                                                              thePrevious);
233   return anAIS;
234 }
235
236 void SketchPlugin_MultiRotation::erase()
237 {
238   static Events_Loop* aLoop = Events_Loop::loop();
239   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
240
241   // Set copy attribute to false on all copied features.
242   AttributeRefListPtr aRefListOfShapes = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
243       data()->attribute(SketchPlugin_Constraint::ENTITY_A()));
244   AttributeRefListPtr aRefListOfRotated = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
245       data()->attribute(SketchPlugin_Constraint::ENTITY_B()));
246
247   if(aRefListOfShapes.get() && aRefListOfRotated.get()) {
248     for(int anIndex = 0; anIndex < aRefListOfRotated->size(); anIndex++) {
249       ObjectPtr anObject = aRefListOfRotated->object(anIndex);
250       if(aRefListOfShapes->isInList(anObject)) {
251         // Don't modify attribute of original features, just skip.
252         continue;
253       }
254       if(anObject.get()) {
255         ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
256         if(aRes.get()) {
257           FeaturePtr aFeature = aRes->document()->feature(aRes);
258           if(aFeature.get()) {
259             AttributeBooleanPtr aBooleanAttr =
260               aFeature->boolean(SketchPlugin_SketchEntity::COPY_ID());
261             if(aBooleanAttr.get()) {
262               if (ModelAPI_Session::get()->isOperation()) // if this is not undo or redo
263                 aBooleanAttr->setValue(false);
264               // Redisplay object as it is not copy anymore.
265               ModelAPI_EventCreator::get()->sendUpdated(aRes, aRedispEvent);
266             }
267           }
268         }
269       }
270     }
271   }
272
273   SketchPlugin_ConstraintBase::erase();
274 }
275
276 ObjectPtr SketchPlugin_MultiRotation::copyFeature(ObjectPtr theObject)
277 {
278   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theObject);
279   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
280   if (!aFeature || !aResult)
281     return ObjectPtr();
282
283   FeaturePtr aNewFeature =
284     SketchPlugin_Sketch::addUniqueNamedCopiedFeature(aFeature, sketch(), true);
285   aNewFeature->execute();
286
287   static Events_ID aRedisplayEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
288   ModelAPI_EventCreator::get()->sendUpdated(aNewFeature, aRedisplayEvent);
289
290   std::shared_ptr<GeomAPI_Shape> aShapeIn = aResult->shape();
291   const std::list<ResultPtr>& aResults = aNewFeature->results();
292   std::list<ResultPtr>::const_iterator anIt = aResults.begin();
293   for (; anIt != aResults.end(); anIt++) {
294     ResultConstructionPtr aRC = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*anIt);
295     if (!aRC) continue;
296     std::shared_ptr<GeomAPI_Shape> aShapeOut = aRC->shape();
297     if ((aShapeIn->isVertex() && aShapeOut->isVertex()) ||
298         (aShapeIn->isEdge() && aShapeOut->isEdge()) ||
299         (aShapeIn->isFace() && aShapeOut->isFace()))
300       return aRC;
301   }
302   return ObjectPtr();
303 }
304
305 /*void SketchPlugin_MultiRotation::rotateFeature(
306     ObjectPtr theInitial, ObjectPtr theTarget,
307     double theCenterX, double theCenterY, double theAngle)
308 {
309   std::shared_ptr<GeomAPI_Pnt2d> aCenter(new GeomAPI_Pnt2d(theCenterX, theCenterY));
310   double cosA = std::cos(theAngle);
311   double sinA = std::sin(theAngle);
312
313   FeaturePtr anInitialFeature = ModelAPI_Feature::feature(theInitial);
314   FeaturePtr aTargetFeature = ModelAPI_Feature::feature(theTarget);
315
316   // block feature update
317   aTargetFeature->data()->blockSendAttributeUpdated(true);
318
319   std::list<AttributePtr> anInitAttrList =
320       anInitialFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
321   std::list<AttributePtr> aTargetAttrList =
322       aTargetFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
323   std::list<AttributePtr>::iterator anInitIt = anInitAttrList.begin();
324   std::list<AttributePtr>::iterator aTargetIt = aTargetAttrList.begin();
325   for (; anInitIt != anInitAttrList.end(); anInitIt++, aTargetIt++) {
326     std::shared_ptr<GeomDataAPI_Point2D> aPointFrom =
327         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anInitIt);
328     std::shared_ptr<GeomDataAPI_Point2D> aPointTo =
329         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*aTargetIt);
330     std::shared_ptr<GeomAPI_XY> aPnt = aPointFrom->pnt()->xy();
331     if (aPnt->distance(aCenter->xy()) > 1.e-7) {
332       std::shared_ptr<GeomAPI_XY> aDir = aPnt->decreased(aCenter->xy());
333       double dx = cosA * aDir->x() - sinA * aDir->y();
334       double dy = sinA * aDir->x() + cosA * aDir->y();
335       aPnt->setX(aCenter->x() + dx);
336       aPnt->setY(aCenter->y() + dy);
337     }
338     aPointTo->setValue(aPnt->x(), aPnt->y());
339   }
340
341   // unblock feature update
342   aTargetFeature->data()->blockSendAttributeUpdated(false);
343 }*/
344
345
346 void SketchPlugin_MultiRotation::attributeChanged(const std::string& theID)
347 {
348   if (theID == ROTATION_LIST_ID()) {
349     AttributeRefListPtr aRotationObjectRefs = reflist(ROTATION_LIST_ID());
350     if (aRotationObjectRefs->size() == 0) {
351       int aNbCopies = integer(NUMBER_OF_OBJECTS_ID())->value()-1;
352       if (aNbCopies <= 0)
353         return;
354
355       // Clear list of objects
356       AttributeRefListPtr aRefListOfRotated = reflist(SketchPlugin_Constraint::ENTITY_B());
357       std::list<ObjectPtr> aTargetList = aRefListOfRotated->list();
358       std::list<ObjectPtr>::iterator aTargetIter = aTargetList.begin();
359       std::set<FeaturePtr> aFeaturesToBeRemoved;
360       while (aTargetIter != aTargetList.end()) {
361         aTargetIter++;
362         for (int i = 0; i < aNbCopies && aTargetIter != aTargetList.end(); i++, aTargetIter++) {
363           aRefListOfRotated->remove(*aTargetIter);
364           // remove the corresponding feature from the sketch
365           FeaturePtr aFeature = ModelAPI_Feature::feature(*aTargetIter);
366           if (aFeature)
367             aFeaturesToBeRemoved.insert(aFeature);
368         }
369       }
370       ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved);
371
372       aRefListOfRotated->clear();
373       reflist(SketchPlugin_Constraint::ENTITY_A())->clear();
374     }
375   }
376   else if (!isUpdatingAngle && real(ANGLE_ID())->isInitialized())
377   {
378     isUpdatingAngle = true;
379     AttributeDoublePtr anAngle = real(ANGLE_ID());
380     if (theID == ANGLE_TYPE() && integer(NUMBER_OF_OBJECTS_ID())->isInitialized()) {
381       if (string(ANGLE_TYPE())->value() != "SingleAngle")
382         anAngle->setValue(anAngle->value() * (integer(NUMBER_OF_OBJECTS_ID())->value() - 1));
383       else
384       {
385         int aNbSplits = integer(NUMBER_OF_OBJECTS_ID())->value();
386         if (anAngle->value() < PERIOD - ANGLETOL)
387           aNbSplits -= 1;
388         anAngle->setValue(anAngle->value() / aNbSplits);
389       }
390     }
391     else if (theID == ANGLE_ID()) {
392       if (anAngle->value() > PERIOD + ANGLETOL || anAngle->value() < -ANGLETOL)
393         anAngle->setValue(anAngle->value() + PERIOD * ceil(-anAngle->value() / PERIOD));
394       if (fabs(anAngle->value() - PERIOD) < ANGLETOL)
395         anAngle->setValue(PERIOD);
396       else if (fabs(anAngle->value()) < ANGLETOL)
397         anAngle->setValue(0.);
398     }
399     isUpdatingAngle = false;
400   }
401 }