Salome HOME
d9926abae676ce169045deb4160a926756524c79
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_STEPImportXCAF.cpp
1 // Copyright (C) 2014-2021  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 <GeomAlgoAPI_STEPImportXCAF.h>
21
22 #include <BRep_Builder.hxx>
23
24 #include <Interface_EntityIterator.hxx>
25 #include <Interface_Graph.hxx>
26 #include <Interface_InterfaceModel.hxx>
27
28 #include <Quantity_Color.hxx>
29
30 #include <StepRepr_DescriptiveRepresentationItem.hxx>
31 #include <StepRepr_ProductDefinitionShape.hxx>
32 #include <StepRepr_PropertyDefinitionRepresentation.hxx>
33 #include <StepRepr_Representation.hxx>
34
35 #include <TDataStd_Name.hxx>
36 #include <TDF_ChildIDIterator.hxx>
37 #include <TDocStd_Document.hxx>
38 #include <TopExp.hxx>
39 #include <TopExp_Explorer.hxx>
40 #include <TopoDS.hxx>
41 #include <Transfer_TransientProcess.hxx>
42 #include <TransferBRep.hxx>
43
44 #include <XCAFApp_Application.hxx>
45 #include <XCAFDoc_DocumentTool.hxx>
46 #include <XCAFDoc_Location.hxx>
47 #include <XCAFDoc_ShapeTool.hxx>
48 #include <XSControl_TransferReader.hxx>
49 #include <XSControl_WorkSession.hxx>
50
51 #include <Locale_Convert.h>
52
53 //=============================================================================
54 TopoDS_Shape getShape(const Handle(Standard_Transient) &theEnti,
55                       const Handle(Transfer_TransientProcess) &theTP)
56 {
57   TopoDS_Shape aResult;
58   Handle(Transfer_Binder) aBinder = theTP->Find(theEnti);
59
60   if (aBinder.IsNull()) {
61     return aResult;
62   }
63
64   aResult = TransferBRep::ShapeResult(aBinder);
65
66   return aResult;
67 }
68
69 //=============================================================================
70 std::shared_ptr<GeomAPI_Shape> readAttributes(STEPCAFControl_Reader &theReader,
71                                std::shared_ptr<ModelAPI_ResultBody> theResultBody,
72                                const bool  theIsMaterials,
73                                std::map< std::wstring,std::list<std::wstring>> &theMaterialShape,
74                                std::string& theError)
75 {
76   // dummy XCAF Application to handle the STEP XCAF Document
77   Handle(XCAFApp_Application) dummy_app = XCAFApp_Application::GetApplication();
78   // XCAF Document to contain the STEP/IGES file itself
79   Handle(TDocStd_Document) adoc;
80
81   dummy_app->NewDocument( TCollection_ExtendedString("MDTV-CAF"), adoc);
82   // transfer STEP/IGES into the document, and get the main label
83   theReader.Transfer(adoc);
84   TDF_Label mainLabel = adoc->Main();
85   Handle_XCAFDoc_ShapeTool shapeTool = XCAFDoc_DocumentTool::ShapeTool(mainLabel);
86   Handle_XCAFDoc_ColorTool colorTool = XCAFDoc_DocumentTool::ColorTool(mainLabel);
87   Handle(XCAFDoc_MaterialTool) materialTool = XCAFDoc_DocumentTool::MaterialTool(mainLabel);
88   // traverse the labels recursively to set attributes on shapes
89   setShapeAttributes(shapeTool, colorTool, materialTool, mainLabel,
90                      TopLoc_Location(),theResultBody,theMaterialShape,false);
91
92   std::shared_ptr<GeomAPI_Shape> ageom =  setgeom(shapeTool,mainLabel,theError);
93
94   STEPControl_Reader aReader = theReader.ChangeReader();
95
96   // BEGIN: reading materials of sub-shapes from file
97   if (theIsMaterials) {
98     TopTools_IndexedMapOfShape anIndices;
99     TopExp::MapShapes(ageom->impl<TopoDS_Shape>(), anIndices);
100
101     Handle(Interface_InterfaceModel) Model = aReader.WS()->Model();
102     Handle(XSControl_TransferReader) TR = aReader.WS()->TransferReader();
103     if (!TR.IsNull()) {
104       Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
105
106       Standard_Integer nb = Model->NbEntities();
107
108       for (Standard_Integer ie = 1; ie <= nb; ie++) {
109         Handle(Standard_Transient) enti = Model->Value(ie);
110
111         // Store materials.
112         storeMaterial(theResultBody,enti, anIndices, TP, mainLabel,theMaterialShape);
113       }
114     }
115   }
116   if (adoc->CanClose() == CDM_CCS_OK)
117     adoc->Close();
118   return ageom;
119 }
120
121 //=============================================================================
122 std::shared_ptr<GeomAPI_Shape> setgeom(const Handle(XCAFDoc_ShapeTool) &theShapeTool,
123                                        const TDF_Label& /*theLabel*/,
124                                        std::string& theError)
125 {
126   BRep_Builder aB;
127   TopoDS_Compound aCompound;
128   aB.MakeCompound(aCompound);
129
130   TDF_LabelSequence aFrshapes;
131   theShapeTool->GetShapes(aFrshapes);
132
133   std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
134
135   if (aFrshapes.Length() == 0) {
136       aGeomShape->setImpl(new TopoDS_Shape());
137       return aGeomShape;
138   } else if (aFrshapes.Length() == 1) {
139     TopoDS_Shape shape = theShapeTool->GetShape(aFrshapes.Value(1));
140     aGeomShape->setImpl(new TopoDS_Shape(shape));
141     return aGeomShape;
142   } else {
143     for (Standard_Integer i=1; i<aFrshapes.Length(); i++) {
144       TopoDS_Shape aS = theShapeTool->GetShape(aFrshapes.Value(i));
145       TDF_Label aLabel = theShapeTool->FindShape(aS, Standard_False);
146       if ( (!aLabel.IsNull()) && (theShapeTool->IsShape(aLabel)) ) {
147         if (theShapeTool->IsFree(aLabel) ) {
148           if (aS.IsNull()) {
149             continue;
150           } else {
151             if (!theShapeTool->IsReference(aLabel) ){
152               for(TDF_ChildIterator anIt(aLabel); anIt.More(); anIt.Next()) {
153                 aB.Add(aCompound, theShapeTool->GetShape(anIt.Value()) );
154               }
155             } else {
156               aB.Add(aCompound, aS);
157             }
158           }
159         }
160       }
161     }
162
163     TopoDS_Shape aShape = aCompound;
164     // Check if any BRep entity has been read, there must be at least a vertex
165     if (!TopExp_Explorer( aShape, TopAbs_VERTEX ).More()) {
166       theError = "No geometrical data in the imported file.";
167       aGeomShape->setImpl(new TopoDS_Shape());
168       return aGeomShape;
169     }
170
171     aGeomShape->setImpl(new TopoDS_Shape(aShape));
172     return aGeomShape;
173   }
174 }
175 //=============================================================================
176 void setShapeAttributes(const Handle(XCAFDoc_ShapeTool) &theShapeTool,
177                         const Handle(XCAFDoc_ColorTool) &theColorTool,
178                         const Handle(XCAFDoc_MaterialTool) &theMaterialTool,
179                         const TDF_Label &theLabel,
180                         const TopLoc_Location &theLoc,
181                         std::shared_ptr<ModelAPI_ResultBody> theResultBody,
182                         std::map< std::wstring,std::list<std::wstring>> &theMaterialShape,
183                         bool theIsRef)
184 {
185   std::wstring aShapeName;
186   Handle(TDataStd_Name) aN;
187
188   if (theLabel.FindAttribute(TDataStd_Name::GetID(), aN)) {
189     TCollection_ExtendedString aName = aN->Get();
190
191     aShapeName =  Locale::Convert::toWString(TCollection_AsciiString(aName).ToCString()) ;
192   }
193
194   TopLoc_Location aPartLoc = theLoc;
195   Handle(XCAFDoc_Location) al;
196   if (theLabel.FindAttribute(XCAFDoc_Location::GetID(), al)) {
197     if (theIsRef)
198       aPartLoc = aPartLoc * al->Get();
199     else
200       aPartLoc = al->Get();
201   }
202
203   TDF_Label aRef;
204   if (theShapeTool->IsReference(theLabel) && theShapeTool->GetReferredShape(theLabel, aRef)) {
205
206     setShapeAttributes( theShapeTool, theColorTool, theMaterialTool, aRef,
207                         aPartLoc,theResultBody,theMaterialShape,true);
208   }
209
210   if (theShapeTool->IsSimpleShape(theLabel) && (theIsRef || theShapeTool->IsFree(theLabel))) {
211
212     TopoDS_Shape aShape = theShapeTool->GetShape(theLabel);
213
214     std::shared_ptr<GeomAPI_Shape> aShapeGeom(new GeomAPI_Shape);
215     if (!theLoc.IsIdentity()) {
216         aShape.Move(theLoc);
217     }
218     aShapeGeom->setImpl(new TopoDS_Shape(aShape));
219     aShapeName = theResultBody->addShapeName(aShapeGeom, aShapeName);
220
221
222     aShape.Location(theIsRef ? theLoc : aPartLoc);
223     int aDim =
224       (aShape.ShapeType() == TopAbs_VERTEX) ?
225         0 :
226         (aShape.ShapeType() == TopAbs_EDGE || aShape.ShapeType() == TopAbs_WIRE) ?
227         1 :
228         (aShape.ShapeType() == TopAbs_FACE ||
229          aShape.ShapeType() == TopAbs_SHELL) ? 2 :3;
230
231     Handle(TCollection_HAsciiString) aMatName;
232     Handle(TCollection_HAsciiString) aMatDescription;
233     Standard_Real aMatDensity;
234     Handle(TCollection_HAsciiString) aMatDensName;
235     Handle(TCollection_HAsciiString) aMatDensValType;
236
237     if (theMaterialTool->GetMaterial(theLabel, aMatName, aMatDescription, aMatDensity,
238                                  aMatDensName, aMatDensValType)) {
239       std::wstring aNameMaterial = Locale::Convert::toWString(aMatName->ToCString());
240
241       theMaterialShape[aNameMaterial].push_back(aShapeName);
242     }
243
244     Quantity_Color aCol;
245     if (theColorTool->GetColor(theLabel, XCAFDoc_ColorGen, aCol)) {
246       double r = aCol.Red(), g = aCol.Green(), b = aCol.Blue();
247       std::vector<int> ColRGB = {int(r*255),int(g*255),int(b*255)};
248       theResultBody->addShapeColor(aShapeName, ColRGB);
249     } else if (theColorTool->GetColor(theLabel, XCAFDoc_ColorSurf, aCol)) {
250       double r = aCol.Red(), g = aCol.Green(), b = aCol.Blue();
251       std::vector<int> aColRGB = {int(r*255),int(g*255),int(b*255)};
252       theResultBody->addShapeColor(aShapeName, aColRGB);
253     } else if (theColorTool->GetColor(theLabel, XCAFDoc_ColorCurv, aCol)) {
254       double aR = aCol.Red(), aG = aCol.Green(), aB = aCol.Blue();
255       std::vector<int> aColRGB = {int(aR*255),int(aG*255),int(aB*255)};
256       theResultBody->addShapeColor(aShapeName, aColRGB);
257     }
258     // check explicit coloring of boundary entities
259     if (aDim == 3) {
260       TopExp_Explorer aXp2(aShape, TopAbs_FACE);
261       while (aXp2.More()) {
262         if (theColorTool->GetColor(aXp2.Current(), XCAFDoc_ColorGen, aCol) ||
263           theColorTool->GetColor(aXp2.Current(), XCAFDoc_ColorSurf, aCol) ||
264           theColorTool->GetColor(aXp2.Current(), XCAFDoc_ColorCurv, aCol)) {
265           double aR = aCol.Red(), aG = aCol.Green(), aB = aCol.Blue();
266           TopoDS_Face aFace = TopoDS::Face(aXp2.Current());
267           std::vector<int> aColRGB = {int(aR*255),int(aG*255),int(aB*255)};
268           std::wstringstream aNameFace;
269           TopoDS_Shape aShapeface = aXp2.Current();
270           if (!theLoc.IsIdentity()){
271                   aShapeface.Move(theLoc);
272           }
273           aShapeGeom->setImpl(new TopoDS_Shape(aShapeface));
274           theResultBody->addShapeColor(
275           theResultBody->addShapeName(aShapeGeom , aNameFace.str()), aColRGB);
276         }
277         aXp2.Next();
278       }
279     }
280   } else {
281     if (!theShapeTool->IsReference(theLabel) ){
282       TopoDS_Shape aShape = theShapeTool->GetShape(theLabel);
283
284       std::shared_ptr<GeomAPI_Shape> aShapeGeom(new GeomAPI_Shape);
285       if (!theLoc.IsIdentity()){
286           aShape.Move(theLoc);
287       }
288       aShapeGeom->setImpl(new TopoDS_Shape(aShape));
289       aShapeName = theResultBody->addShapeName(aShapeGeom, aShapeName);
290     }
291     for(TDF_ChildIterator anIt(theLabel); anIt.More(); anIt.Next()) {
292
293       setShapeAttributes( theShapeTool, theColorTool, theMaterialTool,
294                          anIt.Value(), aPartLoc,theResultBody,theMaterialShape, theIsRef);
295     }
296   }
297 }
298
299 //=============================================================================
300 void storeMaterial( std::shared_ptr<ModelAPI_ResultBody>    theResultBody,
301                     const Handle(Standard_Transient)        &theEnti,
302                     const TopTools_IndexedMapOfShape        &theIndices,
303                     const Handle(Transfer_TransientProcess) &theTP,
304                     const TDF_Label                         &/*theShapeLabel*/,
305                     std::map< std::wstring, std::list<std::wstring>> &theMaterialShape )
306 {
307   // Treat Product Definition Shape only.
308   Handle(StepRepr_ProductDefinitionShape) aPDS =
309     Handle(StepRepr_ProductDefinitionShape)::DownCast(theEnti);
310   Handle(StepBasic_ProductDefinition)     aProdDef;
311
312   if (!aPDS.IsNull()) {
313     // Product Definition Shape ==> Product Definition
314     aProdDef = aPDS->Definition().ProductDefinition();
315   }
316
317   if (!aProdDef.IsNull()) {
318     // Product Definition ==> Property Definition
319     const Interface_Graph    &aGraph = theTP->Graph();
320     Interface_EntityIterator  aSubs  = aGraph.Sharings(aProdDef);
321     TopoDS_Shape              aShape;
322
323     for(aSubs.Start(); aSubs.More(); aSubs.Next()) {
324       Handle(StepRepr_PropertyDefinition) aPropD =
325         Handle(StepRepr_PropertyDefinition)::DownCast(aSubs.Value());
326
327       if (!aPropD.IsNull()) {
328         // Property Definition ==> Representation.
329         Interface_EntityIterator aSubs1 = aGraph.Sharings(aPropD);
330
331         for(aSubs1.Start(); aSubs1.More(); aSubs1.Next()) {
332           Handle(StepRepr_PropertyDefinitionRepresentation) aPDR =
333             Handle(StepRepr_PropertyDefinitionRepresentation)::
334             DownCast(aSubs1.Value());
335
336           if (!aPDR.IsNull()) {
337             // Property Definition ==> Material Name.
338             Handle(StepRepr_Representation) aRepr = aPDR->UsedRepresentation();
339
340             if (!aRepr.IsNull()) {
341               Standard_Integer anIr;
342
343               for(anIr = 1; anIr <= aRepr->NbItems(); anIr++) {
344                 Handle(StepRepr_RepresentationItem) aRI = aRepr->ItemsValue(anIr);
345                 Handle(StepRepr_DescriptiveRepresentationItem) aDRI =
346                   Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(aRI);
347
348                 if (!aDRI.IsNull()) {
349                   // Get shape from Product Definition
350                   Handle(TCollection_HAsciiString) aMatName = aDRI->Name();
351                   if (!aMatName.IsNull()) {
352                     TCollection_ExtendedString
353                       aMatNameExt (aMatName->ToCString());
354
355                     if (aShape.IsNull()) {
356                       //Get the shape.
357                       aShape = getShape(aProdDef, theTP);
358                       if (aShape.IsNull()) {
359                         return;
360                       }
361                     }
362
363                     // as PRODUCT can be included in the main shape
364                     // several times, we look here for all iclusions.
365                     Standard_Integer anISub, aNbSubs = theIndices.Extent();
366
367                     for (anISub = 1; anISub <= aNbSubs; anISub++) {
368                       TopoDS_Shape aSub = theIndices.FindKey(anISub);
369
370                       if (aSub.IsPartner(aShape)) {
371                         std::shared_ptr<GeomAPI_Shape> aShapeGeom(new GeomAPI_Shape);
372                         aShapeGeom->setImpl(new TopoDS_Shape(aSub));
373                         std::wstring aNom = theResultBody->findShapeName(aShapeGeom);
374                         std::wstring aMName= Locale::Convert::toWString(aMatName->ToCString());
375                         theMaterialShape[aMName].push_back(aNom);
376
377                       }
378                     }
379                   }
380                 }
381               }
382             }
383           }
384         }
385       }
386     }
387   }
388 }
389