Salome HOME
Fix for the issue #2721 : multiply selection in viewer problems
[modules/shaper.git] / src / Model / Model_ResultConstruction.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_ResultConstruction.h>
22
23 #include <Model_Data.h>
24 #include <ModelAPI_CompositeFeature.h>
25 #include <GeomAlgoAPI_SketchBuilder.h>
26 #include <ModelAPI_Events.h>
27 #include <Model_Document.h>
28 #include <GeomAPI_PlanarEdges.h>
29 #include <GeomAPI_Shape.h>
30 #include <Events_Loop.h>
31 #include <GeomDataAPI_Point.h>
32 #include <GeomDataAPI_Dir.h>
33
34 #include <TDF_ChildIDIterator.hxx>
35 #include <TNaming_NamedShape.hxx>
36 #include <TNaming_Builder.hxx>
37 #include <TDataStd_IntPackedMap.hxx>
38 #include <TDataStd_Name.hxx>
39 #include <TDataStd_UAttribute.hxx>
40 #include <BRep_Builder.hxx>
41 #include <TopoDS.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Vertex.hxx>
44 #include <TopoDS_ListOfShape.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopTools_MapOfShape.hxx>
47 #include <NCollection_IndexedDataMap.hxx>
48
49 #include <algorithm>
50
51
52 // identifier of the infinite result
53 Standard_GUID kIS_INFINITE("dea8cc5a-53f2-49c1-94e8-a947bed20a9f");
54 // identifier of the result not in history
55 Standard_GUID kIS_IN_HISTORY("a9aec01c-805e-44d1-b5d2-a63f06522f8a");
56
57
58 void Model_ResultConstruction::colorConfigInfo(std::string& theSection, std::string& theName,
59                                        std::string& theDefault)
60 {
61   theSection = "Visualization";
62   theName = "result_construction_color";
63   theDefault = DEFAULT_COLOR();
64 }
65
66 void Model_ResultConstruction::setShape(std::shared_ptr<GeomAPI_Shape> theShape)
67 {
68   if (myShape != theShape) {
69     if (!isInfinite())
70       storeShape(theShape);
71     if (!theShape.get() || !theShape->isEqual(myShape)) {
72       static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
73       ModelAPI_EventCreator::get()->sendUpdated(data()->owner(), anEvent);
74     }
75     myShape = theShape;
76     if (myShape.get() && myShape->shapeType() == GeomAPI_Shape::COMPOUND &&
77       std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(myShape).get() == NULL) {
78       int a= 10;
79     }
80   }
81 }
82
83 std::shared_ptr<GeomAPI_Shape> Model_ResultConstruction::shape()
84 {
85   return myShape;
86 }
87
88 static std::string shortName(
89   std::shared_ptr<ModelAPI_ResultConstruction>& theConstr)
90 {
91   std::string aName = theConstr->data()->name();
92   // remove "-", "/" and "&" command-symbols
93   aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
94   aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
95   aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
96   // remove the last 's', 'e', 'f' and 'r' symbols:
97   // they are used as markers of start/end/forward/reversed indicators
98   static const std::string aSyms("sefr");
99   std::string::iterator aSuffix = aName.end() - 1;
100   while(aSyms.find(*aSuffix) != std::string::npos) {
101     --aSuffix;
102   }
103   aName.erase(aSuffix + 1, aName.end());
104   return aName;
105 }
106
107 bool Model_ResultConstruction::updateShape()
108 {
109   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
110   if (aData && aData->isValid()) {
111     TDF_Label aShapeLab = aData->shapeLab();
112     Handle(TNaming_NamedShape) aNS;
113     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
114       TopoDS_Shape aShape = aNS->Get();
115       if (!aShape.IsNull()) {
116         if (aShape.ShapeType() == TopAbs_COMPOUND) {
117           // restore the sketch planar edges object
118           std::shared_ptr<GeomAPI_PlanarEdges> aBigWire(new GeomAPI_PlanarEdges);
119           aBigWire->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
120           FeaturePtr aSketch =
121             document()->feature(std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner()));
122           std::shared_ptr<GeomDataAPI_Point> anOrigin =
123             std::dynamic_pointer_cast<GeomDataAPI_Point>(aSketch->data()->attribute("Origin"));
124           std::shared_ptr<GeomDataAPI_Dir> aDirX =
125             std::dynamic_pointer_cast<GeomDataAPI_Dir>(aSketch->data()->attribute("DirX"));
126           std::shared_ptr<GeomDataAPI_Dir> aNorm =
127             std::dynamic_pointer_cast<GeomDataAPI_Dir>(aSketch->data()->attribute("Norm"));
128           if (anOrigin.get() && aDirX.get() && aNorm.get()) {
129             aBigWire->setPlane(anOrigin->pnt(), aDirX->dir(), aNorm->dir());
130             myShape = aBigWire;
131             return true;
132           }
133         }
134         // just restore shape
135         GeomShapePtr aGShape(new GeomAPI_Shape);
136         aGShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
137         myShape = aGShape; // restore the sketch sub-components
138         return true;
139       }
140     }
141   }
142   return false;
143 }
144
145 Model_ResultConstruction::Model_ResultConstruction()
146 {
147 }
148
149 bool Model_ResultConstruction::isInHistory()
150 {
151   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
152   if (aData.get() && aData->isValid()) {
153     return !aData->label().IsAttribute(kIS_IN_HISTORY); // by default no attribute, but in history
154   }
155   return true;  // unknown case
156 }
157
158 void Model_ResultConstruction::setIsInHistory(const bool isInHistory)
159 {
160   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
161   if (aData.get() && aData->isValid()) {
162     if (!isInHistory)
163       TDataStd_UAttribute::Set(aData->label(), kIS_IN_HISTORY);
164     else
165       aData->label().ForgetAttribute(kIS_IN_HISTORY);
166   }
167 }
168
169 bool Model_ResultConstruction::isInfinite()
170 {
171   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
172   if (aData.get() && aData->isValid()) {
173     return aData->label().IsAttribute(kIS_INFINITE);
174   }
175   return false;  // unknown case
176 }
177
178 void Model_ResultConstruction::setInfinite(const bool theInfinite)
179 {
180   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
181   if (aData.get() && aData->isValid()) {
182     if (theInfinite)
183       TDataStd_UAttribute::Set(aData->label(), kIS_INFINITE);
184     else
185       aData->label().ForgetAttribute(kIS_INFINITE);
186   }
187 }
188
189 int Model_ResultConstruction::facesNum(const bool theUpdateNaming)
190 {
191   int aResult = 0;
192   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
193   if (aData.get() && aData->isValid()) {
194     TDF_Label aShapeLab = aData->shapeLab();
195     TDF_ChildIDIterator anOldIter(aShapeLab, TDataStd_IntPackedMap::GetID());
196     for (; anOldIter.More(); anOldIter.Next()) {
197       aResult++;
198     }
199   }
200   return aResult;
201 }
202
203 std::shared_ptr<GeomAPI_Face> Model_ResultConstruction::face(const int theIndex)
204 {
205   std::shared_ptr<GeomAPI_Face> aResult;
206   int anIndex = 0;
207   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
208   if (aData.get() && aData->isValid()) {
209     TDF_Label aShapeLab = aData->shapeLab();
210     TDF_ChildIDIterator anOldIter(aShapeLab, TDataStd_IntPackedMap::GetID());
211     for (; anOldIter.More(); anOldIter.Next()) {
212       if (anIndex == theIndex) {
213         Handle(TNaming_NamedShape) aNS;
214         anOldIter.Value()->Label().FindAttribute(TNaming_NamedShape::GetID(), aNS);
215         aResult.reset(new GeomAPI_Face);
216         aResult->setImpl(new TopoDS_Shape(aNS->Get()));
217         break;
218       }
219       anIndex++;
220     }
221   }
222   return aResult;
223 }
224
225 void Model_ResultConstruction::setIsConcealed(const bool theValue)
226 {
227   // do nothing: the construction element is never concealed
228 }
229
230 void Model_ResultConstruction::storeShape(std::shared_ptr<GeomAPI_Shape> theShape)
231 {
232   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
233   if (aData && aData->isValid()) {
234     std::string aMyName = data()->name();
235     TDF_Label aShapeLab = aData->shapeLab();
236     if (!theShape.get() || theShape->isNull()) {
237       aShapeLab.ForgetAllAttributes();
238       TDataStd_Name::Set(aShapeLab, aMyName.c_str()); // restore name forgotten
239       return;
240     }
241     std::shared_ptr<Model_Document> aMyDoc =
242       std::dynamic_pointer_cast<Model_Document>(document());
243     const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
244     if (aShape.ShapeType() == TopAbs_VERTEX) {
245       aShapeLab.ForgetAllAttributes(); // clear all previously stored
246       TNaming_Builder aBuilder(aShapeLab);
247       aBuilder.Generated(aShape);
248       TDataStd_Name::Set(aShapeLab, aMyName.c_str());
249       aMyDoc->addNamingName(aShapeLab, aMyName);
250     } else if (aShape.ShapeType() == TopAbs_EDGE) { // store sub-vertices on sub-labels
251       aShapeLab.ForgetAllAttributes(); // clear all previously stored
252       TNaming_Builder aBuilder(aShapeLab);
253       aBuilder.Generated(aShape);
254
255       TopExp_Explorer anExp(aShape, TopAbs_VERTEX);
256       for(int anIndex = 1; anExp.More(); anExp.Next(), anIndex++) {
257         TDF_Label aSubLab = aShapeLab.FindChild(anIndex);
258         TNaming_Builder aBuilder(aSubLab);
259         aBuilder.Generated(anExp.Current());
260         std::string aVertexName = aMyName + "_" + (anIndex == 1 ? "StartVertex" : "EndVertex");
261         TDataStd_Name::Set(aSubLab, aVertexName.c_str());
262         aMyDoc->addNamingName(aSubLab, aVertexName);
263       }
264       TDataStd_Name::Set(aShapeLab, aMyName.c_str());
265       aMyDoc->addNamingName(aShapeLab, aMyName);
266     } else { // this is probably sketch, so, work with it as with composite
267       std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
268         std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(theShape);
269       if (!aWirePtr.get())
270         return; // unknown case
271       ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
272       FeaturePtr aThisFeature = aMyDoc->feature(aThisPtr);
273       CompositeFeaturePtr aComposite =
274         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aThisFeature);
275       if (!aComposite || aComposite->numberOfSubs() == 0)
276         return; // unknown case
277       // collect indices of curves of current composite
278       NCollection_DataMap<Handle(Geom_Curve), int> aCurvesIndices;
279       NCollection_DataMap<int, TopoDS_Edge> anEdgeIndices;
280       std::map<int, std::string> aComponentsNames; // names of components that lay on index
281       const int aSubNum = aComposite->numberOfSubs();
282       for (int a = 0; a < aSubNum; a++) {
283         FeaturePtr aSub = aComposite->subFeature(a);
284         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
285         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
286         for (; aRes != aResults.cend(); aRes++) {
287           ResultConstructionPtr aConstr =
288             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
289           if (aConstr->shape() && aConstr->shape()->isEdge()) {
290             TopoDS_Edge anEdge = TopoDS::Edge(aConstr->shape()->impl<TopoDS_Shape>());
291             Standard_Real aFirst, aLast;
292             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
293             aCurvesIndices.Bind(aCurve, a);
294             anEdgeIndices.Bind(a, anEdge);
295             aComponentsNames[a] = shortName(aConstr);
296           }
297         }
298       }
299
300       std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
301       GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
302         aWirePtr->norm(), aWirePtr, aFaces);
303       // order is important to store faces in the same order if sketch is created from scratch
304       NCollection_IndexedDataMap<TopoDS_Face, TColStd_ListOfInteger> aNewIndices; // edges indices
305       std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFIter = aFaces.begin();
306       for (; aFIter != aFaces.end(); aFIter++) {
307         std::shared_ptr<GeomAPI_Face> aFace(new GeomAPI_Face(*aFIter));
308         // put them to a label, trying to keep the same faces on the same labels
309         if (aFace.get() && !aFace->isNull()) {
310           TopoDS_Face aTopoFace = TopoDS::Face(aFace->impl<TopoDS_Shape>());
311           aNewIndices.Add(aTopoFace, TColStd_ListOfInteger());
312           // keep new indices of sub-elements used in this face
313           for (TopExp_Explorer anEdges(aTopoFace, TopAbs_EDGE); anEdges.More(); anEdges.Next()) {
314             TopoDS_Edge anEdge = TopoDS::Edge(anEdges.Current());
315             Standard_Real aFirst, aLast;
316             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
317             if (aCurvesIndices.IsBound(aCurve)) {
318               int anIndex = aCurvesIndices.Find(aCurve);
319               if ((aFirst > aLast) != (anEdge.Orientation() == TopAbs_REVERSED))
320                 anIndex = -anIndex;
321               aNewIndices.ChangeFromKey(aTopoFace).Append(anIndex);
322             }
323           }
324         }
325       }
326       NCollection_DataMap<int, TopoDS_Face> aFacesOrder; // faces -> tag where they must be set
327       NCollection_List<TopoDS_Face> anUnorderedFaces; // faces that may be located at any index
328       // searching for the best new candidate to old location
329       NCollection_IndexedDataMap<TopoDS_Face, TColStd_ListOfInteger>::Iterator
330         aNewIter(aNewIndices);
331       for (; aNewIter.More(); aNewIter.Next()) {
332         double aBestFound = 0, aBestNotFound = 1.e+100;
333         int aBestTag = 0;
334         const TColStd_ListOfInteger& aNewInd = aNewIter.Value();
335         // old faces indices where they where located
336         TDF_ChildIDIterator anOldIter(aShapeLab, TDataStd_IntPackedMap::GetID());
337         for (; anOldIter.More(); anOldIter.Next()) {
338           int aTag = anOldIter.Value()->Label().Tag();
339           if (aFacesOrder.IsBound(aTag))
340             continue; // already found a best candidate
341           Handle(TDataStd_IntPackedMap) anOldIndices =
342             Handle(TDataStd_IntPackedMap)::DownCast(anOldIter.Value());
343           double aFound = 0, aNotFound = 0;
344           TColStd_ListOfInteger::Iterator aNewIndIter(aNewInd);
345           for (; aNewIndIter.More(); aNewIndIter.Next()) {
346             if (anOldIndices->Contains(aNewIndIter.Value())) {
347               aFound += 1.;
348             }
349             else if (anOldIndices->Contains(-aNewIndIter.Value())) { // different orientation
350               aFound += 0.001;
351             }
352             else {
353               aNotFound += 1.;
354             }
355           }
356           if (aNotFound < aBestNotFound) {
357             if (aFound > aBestFound) {
358               aBestNotFound = aNotFound;
359               aBestFound = aFound;
360               aBestTag = aTag;
361             }
362           }
363         }
364         if (aBestTag != 0) { // found an appropriate face
365           aFacesOrder.Bind(aBestTag, aNewIter.Key());
366         } else {
367           anUnorderedFaces.Append(aNewIter.Key());
368         }
369       }
370       aShapeLab.ForgetAllAttributes(); // clear all previously stored
371       TDataStd_Name::Set(aShapeLab, aMyName.c_str()); // restore name forgotten
372       TNaming_Builder aBuilder(aShapeLab); // store the compound to get it ready on open of document
373       aBuilder.Generated(aShape);
374       aMyDoc->addNamingName(aShapeLab, aMyName);
375       // set new faces to the labels
376       int aCurrentTag = 1;
377       NCollection_List<TopoDS_Face>::Iterator anUnordered(anUnorderedFaces);
378       for(int aCurrentTag = 1; !aFacesOrder.IsEmpty() || anUnordered.More(); aCurrentTag++) {
379         TopoDS_Face aFaceToPut;
380         if (aFacesOrder.IsBound(aCurrentTag)) {
381           aFaceToPut = aFacesOrder.Find(aCurrentTag);
382           aFacesOrder.UnBind(aCurrentTag);
383         } else if (anUnordered.More()){
384           aFaceToPut = anUnordered.Value();
385           anUnordered.Next();
386         }
387
388         if (!aFaceToPut.IsNull()) {
389           TopTools_MapOfShape aFaceEdges;
390           for(TopExp_Explorer anEdges(aFaceToPut, TopAbs_EDGE); anEdges.More(); anEdges.Next()) {
391             aFaceEdges.Add(anEdges.Current());
392           }
393
394           TDF_Label aLab = aShapeLab.FindChild(aCurrentTag);
395           TNaming_Builder aFaceBuilder(aLab);
396           aFaceBuilder.Generated(aFaceToPut);
397           // store also indices of the new face edges
398           Handle(TDataStd_IntPackedMap) aNewMap = TDataStd_IntPackedMap::Set(aLab);
399           const TColStd_ListOfInteger& aNewInd = aNewIndices.FindFromKey(aFaceToPut);
400           std::stringstream aName;
401           aName<<"Face";
402           TopExp_Explorer aPutEdges(aFaceToPut, TopAbs_EDGE);
403           TNaming_Builder* anEdgesBuilder = 0;
404           for(TColStd_ListOfInteger::Iterator anIter(aNewInd); anIter.More(); anIter.Next()) {
405             int anIndex = anIter.Value();
406             int aModIndex = anIndex > 0 ? anIndex : -anIndex;
407             aNewMap->Add(anIndex);
408             aName<<"-"<<aComponentsNames[aModIndex];
409             if (anIter.Value() > 0)
410               aName<<"f";
411             else
412               aName<<"r";
413             // collect all edges of the face which are modified in sub-label of the face
414             if (anEdgeIndices.IsBound(aModIndex) &&
415                 !aFaceEdges.Contains(anEdgeIndices.Find(aModIndex))) {
416               if (!anEdgesBuilder) {
417                 TDF_Label anEdgesLabel = aLab.FindChild(1);
418                 anEdgesBuilder = new TNaming_Builder(anEdgesLabel);
419                 std::ostringstream aSubName;
420                 // tag is needed for Test1922 to distinguish sub-edges of different faces
421                 aSubName<<"SubEdge_"<<aCurrentTag;
422                 TDataStd_Name::Set(anEdgesLabel, aSubName.str().c_str());
423               }
424               anEdgesBuilder->Modify(anEdgeIndices.Find(aModIndex), aPutEdges.Current());
425             }
426             aPutEdges.Next();
427           }
428           TDataStd_Name::Set(aLab, TCollection_ExtendedString(aName.str().c_str()));
429           aMyDoc->addNamingName(aLab, aName.str());
430           // put also wires to sub-labels to correctly select them instead of collection by edges
431           int aWireTag = 2; // first tag is for SubEdge-s
432           for(TopExp_Explorer aWires(aFaceToPut, TopAbs_WIRE); aWires.More(); aWires.Next()) {
433             TDF_Label aWireLab = aLab.FindChild(aWireTag);
434             TNaming_Builder aWireBuilder(aWireLab);
435             aWireBuilder.Generated(aWires.Current());
436             std::ostringstream aWireName;
437             aWireName<<aName.str()<<"_wire";
438             if (aWireTag > 2)
439               aWireName<<"_"<<aWireTag - 1;
440             TDataStd_Name::Set(aWireLab, aWireName.str().c_str());
441             aMyDoc->addNamingName(aWireLab, aWireName.str());
442             aWireTag++;
443           }
444         }
445       }
446     }
447   }
448 }