Salome HOME
Update copyrights
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_MultiRotation.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 "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   std::shared_ptr<ModelAPI_Data> aData = data();
104   AttributeRefListPtr aRefListOfShapes = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
105       aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
106   AttributeRefListPtr aRefListOfRotated = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
107       aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
108   int aCurrentNbCopies = aRefListOfShapes->size() ?
109       aRefListOfRotated->size() / aRefListOfShapes->size() - 1 : 0;
110   std::list<ObjectPtr> anInitialList = aRefListOfShapes->list();
111   std::list<ObjectPtr> aTargetList = aRefListOfRotated->list();
112   std::list<ObjectPtr> anAddition;
113   std::vector<bool> isUsed(anInitialList.size(), false);
114   // collect new items and check the items to remove
115   for(int anInd = 0; anInd < aRotationObjectRefs->size(); anInd++) {
116     ObjectPtr anObject = aRotationObjectRefs->object(anInd);
117     std::list<ObjectPtr>::const_iterator anIt = anInitialList.begin();
118     std::vector<bool>::iterator aUsedIt = isUsed.begin();
119     for (; anIt != anInitialList.end(); anIt++, aUsedIt++)
120       if (*anIt == anObject) {
121         *aUsedIt = true;
122         break;
123       }
124     if (anIt == anInitialList.end())
125       anAddition.push_back(anObject);
126   }
127   // remove unused items
128   std::list<ObjectPtr>::iterator anInitIter = anInitialList.begin();
129   std::list<ObjectPtr>::iterator aTargetIter = aTargetList.begin();
130   std::vector<bool>::iterator aUsedIter = isUsed.begin();
131   std::set<FeaturePtr> aFeaturesToBeRemoved;
132   for (; aUsedIter != isUsed.end(); aUsedIter++) {
133     if (!(*aUsedIter)) {
134       aRefListOfShapes->remove(*anInitIter);
135       aRefListOfRotated->remove(*aTargetIter++);
136       for (int i = 0; i < aCurrentNbCopies && aTargetIter != aTargetList.end();
137            i++, aTargetIter++) {
138         aRefListOfRotated->remove(*aTargetIter);
139         // remove the corresponding feature from the sketch
140         ResultConstructionPtr aRC =
141             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aTargetIter);
142         DocumentPtr aDoc = aRC ? aRC->document() : DocumentPtr();
143         FeaturePtr aFeature =  aDoc ? aDoc->feature(aRC) : FeaturePtr();
144         if (aFeature)
145           aFeaturesToBeRemoved.insert(aFeature);
146       }
147     } else {
148       for (int i = 0; i <= aNbCopies && aTargetIter != aTargetList.end(); i++)
149         aTargetIter++;
150     }
151     if (anInitIter != anInitialList.end())
152       anInitIter++;
153   }
154   ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved);
155   // change number of copies
156   if (aCurrentNbCopies != 0 && aNbCopies != aCurrentNbCopies) {
157     bool isAdd = aNbCopies > aCurrentNbCopies;
158     int aMinCopies = isAdd ? aCurrentNbCopies : aNbCopies;
159     int aMaxCopies = isAdd ? aNbCopies : aCurrentNbCopies;
160     int ind = 0;
161
162     aTargetList = aRefListOfRotated->list();
163     aTargetIter = aTargetList.begin();
164     ObjectPtr anObjToCopy = *aTargetIter;
165     std::set<FeaturePtr> aFeaturesToBeRemoved;
166     while (aTargetIter != aTargetList.end()) {
167       aRefListOfRotated->remove(*aTargetIter);
168       aTargetIter++;
169       ind++;
170       if (ind > aMinCopies && ind <=aMaxCopies) {
171         while (ind <= aMaxCopies) {
172           if (isAdd) {
173             // Add new shifted item
174             ObjectPtr anObject = copyFeature(anObjToCopy);
175             aTargetList.insert(aTargetIter, anObject);
176           } else {
177             // remove object
178             std::list<ObjectPtr>::iterator aRemoveIt = aTargetIter++;
179             ObjectPtr anObject = *aRemoveIt;
180             aTargetList.erase(aRemoveIt);
181             aRefListOfRotated->remove(anObject);
182             // remove the corresponding feature from the sketch
183             ResultConstructionPtr aRC =
184                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anObject);
185             DocumentPtr aDoc = aRC ? aRC->document() : DocumentPtr();
186             FeaturePtr aFeature =  aDoc ? aDoc->feature(aRC) : FeaturePtr();
187             if (aFeature)
188               aFeaturesToBeRemoved.insert(aFeature);
189           }
190           ind++;
191         }
192         ind = 0;
193         if (aTargetIter != aTargetList.end())
194           anObjToCopy = *aTargetIter;
195       }
196     }
197     ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved);
198
199     for (aTargetIter = aTargetList.begin(); aTargetIter != aTargetList.end(); aTargetIter++)
200       aRefListOfRotated->append(*aTargetIter);
201   }
202   // add new items
203   std::list<ObjectPtr>::iterator anAddIter = anAddition.begin();
204   for (; anAddIter != anAddition.end(); anAddIter++) {
205     aRefListOfShapes->append(*anAddIter);
206     aRefListOfRotated->append(*anAddIter);
207     for (int i = 0; i < aNbCopies; i++) {
208       ObjectPtr anObject = copyFeature(*anAddIter);
209       aRefListOfRotated->append(anObject);
210     }
211   }
212
213 ////  if (fabs(anAngle) > 1.e-12) {
214 ////    // Recalculate positions of features
215 ////    aTargetList = aRefListOfRotated->list();
216 ////    aTargetIter = aTargetList.begin();
217 ////    while (aTargetIter != aTargetList.end()) {
218 ////      ObjectPtr anInitialObject = *aTargetIter++;
219 ////      for (int i = 0; i < aNbCopies && aTargetIter != aTargetList.end(); i++, aTargetIter++)
220 //// rotateFeature(anInitialObject, *aTargetIter, aCenter->x(), aCenter->y(), anAngle * (i + 1));
221 ////    }
222 ////  }
223
224   // send events to update the sub-features by the solver
225   if (isUpdateFlushed)
226     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
227 }
228
229 AISObjectPtr SketchPlugin_MultiRotation::getAISObject(AISObjectPtr thePrevious)
230 {
231   if (!sketch())
232     return thePrevious;
233
234   AISObjectPtr anAIS = SketcherPrs_Factory::rotateConstraint(this, sketch(),
235                                                              thePrevious);
236   return anAIS;
237 }
238
239 void SketchPlugin_MultiRotation::erase()
240 {
241   static Events_Loop* aLoop = Events_Loop::loop();
242   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
243
244   // Set copy attribute to false on all copied features.
245   AttributeRefListPtr aRefListOfShapes = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
246       data()->attribute(SketchPlugin_Constraint::ENTITY_A()));
247   AttributeRefListPtr aRefListOfRotated = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
248       data()->attribute(SketchPlugin_Constraint::ENTITY_B()));
249
250   if(aRefListOfShapes.get() && aRefListOfRotated.get()) {
251     for(int anIndex = 0; anIndex < aRefListOfRotated->size(); anIndex++) {
252       ObjectPtr anObject = aRefListOfRotated->object(anIndex);
253       if(aRefListOfShapes->isInList(anObject)) {
254         // Don't modify attribute of original features, just skip.
255         continue;
256       }
257       if(anObject.get()) {
258         ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
259         if(aRes.get()) {
260           FeaturePtr aFeature = aRes->document()->feature(aRes);
261           if(aFeature.get()) {
262             AttributeBooleanPtr aBooleanAttr =
263               aFeature->boolean(SketchPlugin_SketchEntity::COPY_ID());
264             if(aBooleanAttr.get()) {
265               if (ModelAPI_Session::get()->isOperation()) // if this is not undo or redo
266                 aBooleanAttr->setValue(false);
267               // Redisplay object as it is not copy anymore.
268               ModelAPI_EventCreator::get()->sendUpdated(aRes, aRedispEvent);
269             }
270           }
271         }
272       }
273     }
274   }
275
276   SketchPlugin_ConstraintBase::erase();
277 }
278
279 ObjectPtr SketchPlugin_MultiRotation::copyFeature(ObjectPtr theObject)
280 {
281   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theObject);
282   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
283   if (!aFeature || !aResult)
284     return ObjectPtr();
285
286   FeaturePtr aNewFeature =
287     SketchPlugin_Sketch::addUniqueNamedCopiedFeature(aFeature, sketch(), true);
288   aNewFeature->execute();
289
290   static Events_ID aRedisplayEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
291   ModelAPI_EventCreator::get()->sendUpdated(aNewFeature, aRedisplayEvent);
292
293   std::shared_ptr<GeomAPI_Shape> aShapeIn = aResult->shape();
294   const std::list<ResultPtr>& aResults = aNewFeature->results();
295   std::list<ResultPtr>::const_iterator anIt = aResults.begin();
296   for (; anIt != aResults.end(); anIt++) {
297     ResultConstructionPtr aRC = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*anIt);
298     if (!aRC) continue;
299     std::shared_ptr<GeomAPI_Shape> aShapeOut = aRC->shape();
300     if ((aShapeIn->isVertex() && aShapeOut->isVertex()) ||
301         (aShapeIn->isEdge() && aShapeOut->isEdge()) ||
302         (aShapeIn->isFace() && aShapeOut->isFace()))
303       return aRC;
304   }
305   return ObjectPtr();
306 }
307
308 /*void SketchPlugin_MultiRotation::rotateFeature(
309     ObjectPtr theInitial, ObjectPtr theTarget,
310     double theCenterX, double theCenterY, double theAngle)
311 {
312   std::shared_ptr<GeomAPI_Pnt2d> aCenter(new GeomAPI_Pnt2d(theCenterX, theCenterY));
313   double cosA = std::cos(theAngle);
314   double sinA = std::sin(theAngle);
315
316   FeaturePtr anInitialFeature = ModelAPI_Feature::feature(theInitial);
317   FeaturePtr aTargetFeature = ModelAPI_Feature::feature(theTarget);
318
319   // block feature update
320   aTargetFeature->data()->blockSendAttributeUpdated(true);
321
322   std::list<AttributePtr> anInitAttrList =
323       anInitialFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
324   std::list<AttributePtr> aTargetAttrList =
325       aTargetFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
326   std::list<AttributePtr>::iterator anInitIt = anInitAttrList.begin();
327   std::list<AttributePtr>::iterator aTargetIt = aTargetAttrList.begin();
328   for (; anInitIt != anInitAttrList.end(); anInitIt++, aTargetIt++) {
329     std::shared_ptr<GeomDataAPI_Point2D> aPointFrom =
330         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anInitIt);
331     std::shared_ptr<GeomDataAPI_Point2D> aPointTo =
332         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*aTargetIt);
333     std::shared_ptr<GeomAPI_XY> aPnt = aPointFrom->pnt()->xy();
334     if (aPnt->distance(aCenter->xy()) > 1.e-7) {
335       std::shared_ptr<GeomAPI_XY> aDir = aPnt->decreased(aCenter->xy());
336       double dx = cosA * aDir->x() - sinA * aDir->y();
337       double dy = sinA * aDir->x() + cosA * aDir->y();
338       aPnt->setX(aCenter->x() + dx);
339       aPnt->setY(aCenter->y() + dy);
340     }
341     aPointTo->setValue(aPnt->x(), aPnt->y());
342   }
343
344   // unblock feature update
345   aTargetFeature->data()->blockSendAttributeUpdated(false);
346 }*/
347
348
349 void SketchPlugin_MultiRotation::attributeChanged(const std::string& theID)
350 {
351   if (theID == ROTATION_LIST_ID()) {
352     AttributeRefListPtr aRotationObjectRefs = reflist(ROTATION_LIST_ID());
353     if (aRotationObjectRefs->size() == 0) {
354       int aNbCopies = integer(NUMBER_OF_OBJECTS_ID())->value()-1;
355       if (aNbCopies <= 0)
356         return;
357
358       // Clear list of objects
359       AttributeRefListPtr aRefListOfRotated = reflist(SketchPlugin_Constraint::ENTITY_B());
360       std::list<ObjectPtr> aTargetList = aRefListOfRotated->list();
361       std::list<ObjectPtr>::iterator aTargetIter = aTargetList.begin();
362       std::set<FeaturePtr> aFeaturesToBeRemoved;
363       while (aTargetIter != aTargetList.end()) {
364         aTargetIter++;
365         for (int i = 0; i < aNbCopies && aTargetIter != aTargetList.end(); i++, aTargetIter++) {
366           aRefListOfRotated->remove(*aTargetIter);
367           // remove the corresponding feature from the sketch
368           FeaturePtr aFeature = ModelAPI_Feature::feature(*aTargetIter);
369           if (aFeature)
370             aFeaturesToBeRemoved.insert(aFeature);
371         }
372       }
373       ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved);
374
375       aRefListOfRotated->clear();
376       reflist(SketchPlugin_Constraint::ENTITY_A())->clear();
377     }
378   }
379   else if (!isUpdatingAngle && real(ANGLE_ID())->isInitialized())
380   {
381     isUpdatingAngle = true;
382     AttributeDoublePtr anAngle = real(ANGLE_ID());
383     if (theID == ANGLE_TYPE() && integer(NUMBER_OF_OBJECTS_ID())->isInitialized()) {
384       if (string(ANGLE_TYPE())->value() != "SingleAngle")
385         anAngle->setValue(anAngle->value() * (integer(NUMBER_OF_OBJECTS_ID())->value() - 1));
386       else
387       {
388         int aNbSplits = integer(NUMBER_OF_OBJECTS_ID())->value();
389         if (anAngle->value() < PERIOD - ANGLETOL)
390           aNbSplits -= 1;
391         anAngle->setValue(anAngle->value() / aNbSplits);
392       }
393     }
394     else if (theID == ANGLE_ID()) {
395       if (anAngle->value() > PERIOD + ANGLETOL || anAngle->value() < -ANGLETOL)
396         anAngle->setValue(anAngle->value() + PERIOD * ceil(-anAngle->value() / PERIOD));
397       if (fabs(anAngle->value() - PERIOD) < ANGLETOL)
398         anAngle->setValue(PERIOD);
399       else if (fabs(anAngle->value()) < ANGLETOL)
400         anAngle->setValue(0.);
401     }
402     isUpdatingAngle = false;
403   }
404 }