0026457: Failed build with OCCT_DEBUG enabled
[occt.git] / src / STEPCAFControl / STEPCAFControl_Reader.cxx
1 // Created on: 2000-08-15
2 // Created by: Andrey BETENEV
3 // Copyright (c) 2000-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16
17 #include <BRep_Builder.hxx>
18 #include <Interface_EntityIterator.hxx>
19 #include <Interface_InterfaceModel.hxx>
20 #include <Interface_Static.hxx>
21 #include <NCollection_DataMap.hxx>
22 #include <OSD_Path.hxx>
23 #include <Quantity_Color.hxx>
24 #include <StepAP214_AppliedExternalIdentificationAssignment.hxx>
25 #include <StepBasic_ConversionBasedUnitAndLengthUnit.hxx>
26 #include <StepBasic_ConversionBasedUnitAndMassUnit.hxx>
27 #include <StepBasic_DerivedUnit.hxx>
28 #include <StepBasic_DerivedUnitElement.hxx>
29 #include <StepBasic_MeasureValueMember.hxx>
30 #include <StepBasic_MeasureWithUnit.hxx>
31 #include <StepBasic_NamedUnit.hxx>
32 #include <StepBasic_Product.hxx>
33 #include <StepBasic_ProductDefinition.hxx>
34 #include <StepBasic_ProductDefinitionFormation.hxx>
35 #include <StepBasic_ProductDefinitionRelationship.hxx>
36 #include <StepBasic_SiUnit.hxx>
37 #include <StepBasic_Unit.hxx>
38 #include <STEPCAFControl_Controller.hxx>
39 #include <STEPCAFControl_DataMapIteratorOfDataMapOfShapePD.hxx>
40 #include <STEPCAFControl_DataMapOfPDExternFile.hxx>
41 #include <STEPCAFControl_DataMapOfSDRExternFile.hxx>
42 #include <STEPCAFControl_DataMapOfShapePD.hxx>
43 #include <STEPCAFControl_DictionaryOfExternFile.hxx>
44 #include <STEPCAFControl_ExternFile.hxx>
45 #include <STEPCAFControl_Reader.hxx>
46 #include <STEPConstruct.hxx>
47 #include <STEPConstruct_Assembly.hxx>
48 #include <STEPConstruct_ExternRefs.hxx>
49 #include <STEPConstruct_Styles.hxx>
50 #include <STEPConstruct_Tool.hxx>
51 #include <STEPConstruct_UnitContext.hxx>
52 #include <STEPConstruct_ValidationProps.hxx>
53 #include <STEPControl_Reader.hxx>
54 #include <StepDimTol_AngularityTolerance.hxx>
55 #include <StepDimTol_CircularRunoutTolerance.hxx>
56 #include <StepDimTol_CoaxialityTolerance.hxx>
57 #include <StepDimTol_ConcentricityTolerance.hxx>
58 #include <StepDimTol_CylindricityTolerance.hxx>
59 #include <StepDimTol_Datum.hxx>
60 #include <StepDimTol_DatumFeature.hxx>
61 #include <StepDimTol_DatumReference.hxx>
62 #include <StepDimTol_FlatnessTolerance.hxx>
63 #include <StepDimTol_GeometricTolerance.hxx>
64 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
65 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
66 #include <StepDimTol_HArray1OfDatumReference.hxx>
67 #include <StepDimTol_LineProfileTolerance.hxx>
68 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
69 #include <StepDimTol_ParallelismTolerance.hxx>
70 #include <StepDimTol_PerpendicularityTolerance.hxx>
71 #include <StepDimTol_PositionTolerance.hxx>
72 #include <StepDimTol_RoundnessTolerance.hxx>
73 #include <StepDimTol_StraightnessTolerance.hxx>
74 #include <StepDimTol_SurfaceProfileTolerance.hxx>
75 #include <StepDimTol_SymmetryTolerance.hxx>
76 #include <StepDimTol_TotalRunoutTolerance.hxx>
77 #include <StepRepr_AssemblyComponentUsage.hxx>
78 #include <StepRepr_CharacterizedDefinition.hxx>
79 #include <StepRepr_DescriptiveRepresentationItem.hxx>
80 #include <StepRepr_HArray1OfRepresentationItem.hxx>
81 #include <StepRepr_MeasureRepresentationItem.hxx>
82 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
83 #include <StepRepr_ProductDefinitionShape.hxx>
84 #include <StepRepr_PropertyDefinition.hxx>
85 #include <StepRepr_PropertyDefinitionRepresentation.hxx>
86 #include <StepRepr_Representation.hxx>
87 #include <StepRepr_RepresentationItem.hxx>
88 #include <StepRepr_RepresentationRelationship.hxx>
89 #include <StepRepr_RepresentedDefinition.hxx>
90 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
91 #include <StepRepr_SequenceOfRepresentationItem.hxx>
92 #include <StepRepr_ShapeAspect.hxx>
93 #include <StepRepr_ShapeAspectRelationship.hxx>
94 #include <StepRepr_ShapeRepresentationRelationship.hxx>
95 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
96 #include <StepRepr_ValueRange.hxx>
97 #include <StepShape_AdvancedFace.hxx>
98 #include <StepShape_ClosedShell.hxx>
99 #include <StepShape_ConnectedFaceSet.hxx>
100 #include <StepShape_ContextDependentShapeRepresentation.hxx>
101 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
102 #include <StepShape_DimensionalSize.hxx>
103 #include <StepShape_EdgeCurve.hxx>
104 #include <StepShape_EdgeLoop.hxx>
105 #include <StepShape_GeometricSet.hxx>
106 #include <StepShape_HArray1OfFace.hxx>
107 #include <StepShape_HArray1OfFaceBound.hxx>
108 #include <StepShape_HArray1OfOrientedEdge.hxx>
109 #include <StepShape_HArray1OfShell.hxx>
110 #include <StepShape_Loop.hxx>
111 #include <StepShape_ManifoldSolidBrep.hxx>
112 #include <StepShape_OpenShell.hxx>
113 #include <StepShape_ShapeDefinitionRepresentation.hxx>
114 #include <StepShape_ShapeDimensionRepresentation.hxx>
115 #include <StepShape_ShapeRepresentation.hxx>
116 #include <StepShape_ShellBasedSurfaceModel.hxx>
117 #include <StepShape_SolidModel.hxx>
118 #include <StepShape_Vertex.hxx>
119 #include <StepVisual_Invisibility.hxx>
120 #include <StepVisual_LayeredItem.hxx>
121 #include <StepVisual_PresentationLayerAssignment.hxx>
122 #include <StepVisual_PresentationStyleByContext.hxx>
123 #include <StepVisual_StyleContextSelect.hxx>
124 #include <StepVisual_StyledItem.hxx>
125 #include <TCollection_AsciiString.hxx>
126 #include <TCollection_HAsciiString.hxx>
127 #include <TColStd_HArray1OfReal.hxx>
128 #include <TColStd_HArray1OfTransient.hxx>
129 #include <TColStd_HSequenceOfTransient.hxx>
130 #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
131 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
132 #include <TColStd_MapOfTransient.hxx>
133 #include <TColStd_SequenceOfHAsciiString.hxx>
134 #include <TDataStd_Name.hxx>
135 #include <TDataStd_TreeNode.hxx>
136 #include <TDataStd_UAttribute.hxx>
137 #include <TDF_Label.hxx>
138 #include <TDF_Tool.hxx>
139 #include <TDocStd_Document.hxx>
140 #include <TNaming_NamedShape.hxx>
141 #include <TopoDS_Compound.hxx>
142 #include <TopoDS_Iterator.hxx>
143 #include <TopoDS_Shape.hxx>
144 #include <TopTools_ListIteratorOfListOfShape.hxx>
145 #include <TopTools_ListOfShape.hxx>
146 #include <TopTools_MapOfShape.hxx>
147 #include <Transfer_Binder.hxx>
148 #include <Transfer_TransientProcess.hxx>
149 #include <TransferBRep.hxx>
150 #include <XCAFDoc.hxx>
151 #include <XCAFDoc_Area.hxx>
152 #include <XCAFDoc_Centroid.hxx>
153 #include <XCAFDoc_ColorTool.hxx>
154 #include <XCAFDoc_DataMapOfShapeLabel.hxx>
155 #include <XCAFDoc_DimTolTool.hxx>
156 #include <XCAFDoc_DocumentTool.hxx>
157 #include <XCAFDoc_GraphNode.hxx>
158 #include <XCAFDoc_LayerTool.hxx>
159 #include <XCAFDoc_MaterialTool.hxx>
160 #include <XCAFDoc_ShapeTool.hxx>
161 #include <XCAFDoc_Volume.hxx>
162 #include <XSControl_TransferReader.hxx>
163 #include <XSControl_WorkSession.hxx>
164
165 // skl 21.08.2003 for reading G&DT
166 //#include <StepRepr_CompoundItemDefinition.hxx>
167 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
168 //#include <StepBasic_ConversionBasedUnit.hxx>
169 //#include <TDataStd_Real.hxx>
170 //#include <TDataStd_Constraint.hxx>
171 //#include <TDataStd_ConstraintEnum.hxx>
172 //#include <TNaming_Tool.hxx>
173 //#include <AIS_InteractiveObject.hxx>
174 //#include <TPrsStd_ConstraintTools.hxx>
175 //#include <AIS_DiameterDimension.hxx>
176 //#include <TPrsStd_Position.hxx>
177 //#include <TPrsStd_AISPresentation.hxx>
178 //#include <TNaming_Builder.hxx>
179 #ifdef OCCT_DEBUG
180 //! Converts address of the passed shape (TShape) to string.
181 //! \param theShape [in] Shape to dump.
182 //! \return corresponding string.
183 TCollection_AsciiString AddrToString(const TopoDS_Shape& theShape)
184 {
185   std::string anAddrStr;
186   std::ostringstream ost;
187   ost << theShape.TShape().get();
188   anAddrStr = ost.str();
189
190   TCollection_AsciiString aStr =
191     TCollection_AsciiString("[").Cat( anAddrStr.c_str() ).Cat("]");
192
193   return aStr;
194 }
195 #endif
196
197 //=======================================================================
198 //function : IsEqual
199 //purpose  : global function to check equality of topological shapes
200 //=======================================================================
201
202 inline Standard_Boolean IsEqual(const TopoDS_Shape& theShape1,
203                                 const TopoDS_Shape& theShape2) 
204 {
205   return theShape1.IsEqual(theShape2);
206 }
207
208 //=======================================================================
209 //function : AllocateSubLabel
210 //purpose  :
211 //=======================================================================
212
213 static TDF_Label AllocateSubLabel(TDF_Label& theRoot)
214 {
215   return TDF_TagSource::NewChild(theRoot);
216 }
217
218 //=======================================================================
219 //function : STEPCAFControl_Reader
220 //purpose  : 
221 //=======================================================================
222
223 STEPCAFControl_Reader::STEPCAFControl_Reader ():
224        myColorMode( Standard_True ),
225        myNameMode ( Standard_True ),
226        myLayerMode( Standard_True ),
227        myPropsMode( Standard_True ),
228            mySHUOMode ( Standard_False ),
229        myGDTMode  ( Standard_True ),
230        myMatMode  ( Standard_True )
231 {
232   STEPCAFControl_Controller::Init();
233   myFiles = new STEPCAFControl_DictionaryOfExternFile;
234 }
235
236
237 //=======================================================================
238 //function : STEPCAFControl_Reader
239 //purpose  : 
240 //=======================================================================
241
242 STEPCAFControl_Reader::STEPCAFControl_Reader (const Handle(XSControl_WorkSession)& WS,
243                                               const Standard_Boolean scratch) :
244        myColorMode( Standard_True ),
245        myNameMode ( Standard_True ),
246        myLayerMode( Standard_True ),
247        myPropsMode( Standard_True ),
248            mySHUOMode ( Standard_False ),
249        myGDTMode  ( Standard_True ),
250        myMatMode  ( Standard_True )
251 {
252   STEPCAFControl_Controller::Init();
253   Init ( WS, scratch );
254 }
255
256
257 //=======================================================================
258 //function : Init
259 //purpose  : 
260 //=======================================================================
261
262 void STEPCAFControl_Reader::Init (const Handle(XSControl_WorkSession)& WS,
263                                   const Standard_Boolean scratch)
264 {
265 // necessary only in Writer, to set good actor:  WS->SelectNorm ( "STEP" );
266   myReader.SetWS (WS,scratch);
267   myFiles = new STEPCAFControl_DictionaryOfExternFile;
268 }
269
270
271 //=======================================================================
272 //function : ReadFile
273 //purpose  : 
274 //=======================================================================
275
276 IFSelect_ReturnStatus STEPCAFControl_Reader::ReadFile (const Standard_CString filename)
277 {
278   return myReader.ReadFile ( filename );
279 }
280
281
282 //=======================================================================
283 //function : NbRootsForTransfer
284 //purpose  : 
285 //=======================================================================
286
287 Standard_Integer STEPCAFControl_Reader::NbRootsForTransfer () 
288 {
289   return myReader.NbRootsForTransfer();
290 }
291
292
293 //=======================================================================
294 //function : TransferOneRoot
295 //purpose  : 
296 //=======================================================================
297
298 Standard_Boolean STEPCAFControl_Reader::TransferOneRoot (const Standard_Integer num,
299                                                          Handle(TDocStd_Document) &doc) 
300 {
301   TDF_LabelSequence Lseq;
302   return Transfer ( myReader, num, doc, Lseq );
303 }
304
305
306 //=======================================================================
307 //function : Transfer
308 //purpose  : 
309 //=======================================================================
310
311 Standard_Boolean STEPCAFControl_Reader::Transfer (Handle(TDocStd_Document) &doc)
312 {
313   TDF_LabelSequence Lseq;
314   return Transfer ( myReader, 0, doc, Lseq );
315 }
316
317
318 //=======================================================================
319 //function : Perform
320 //purpose  : 
321 //=======================================================================
322
323 Standard_Boolean STEPCAFControl_Reader::Perform (const Standard_CString filename,
324                                                  Handle(TDocStd_Document) &doc)
325 {
326   if ( ReadFile ( filename ) != IFSelect_RetDone ) return Standard_False;
327   return Transfer ( doc );
328 }
329   
330
331 //=======================================================================
332 //function : Perform
333 //purpose  : 
334 //=======================================================================
335
336 Standard_Boolean STEPCAFControl_Reader::Perform (const TCollection_AsciiString &filename,
337                                                  Handle(TDocStd_Document) &doc)
338 {
339   if ( ReadFile ( filename.ToCString() ) != IFSelect_RetDone ) return Standard_False;
340   return Transfer ( doc );
341 }
342   
343
344 //=======================================================================
345 //function : ExternFiles
346 //purpose  : 
347 //=======================================================================
348
349 const Handle(STEPCAFControl_DictionaryOfExternFile) &STEPCAFControl_Reader::ExternFiles () const
350 {
351   return myFiles;
352 }
353         
354
355 //=======================================================================
356 //function : ExternFile
357 //purpose  : 
358 //=======================================================================
359
360 Standard_Boolean STEPCAFControl_Reader::ExternFile (const Standard_CString name,
361                                                     Handle(STEPCAFControl_ExternFile) &ef) const
362 {
363   ef.Nullify();
364   if ( myFiles.IsNull() || ! myFiles->HasItem ( name ) ) 
365     return Standard_False;
366   ef = myFiles->Item ( name );
367   return Standard_True;
368 }
369
370
371 //=======================================================================
372 //function : Reader
373 //purpose  : 
374 //=======================================================================
375
376 STEPControl_Reader &STEPCAFControl_Reader::ChangeReader () 
377 {
378   return myReader;
379 }
380   
381
382 //=======================================================================
383 //function : Reader
384 //purpose  : 
385 //=======================================================================
386
387 const STEPControl_Reader &STEPCAFControl_Reader::Reader () const
388 {
389   return myReader;
390 }
391   
392
393 //=======================================================================
394 //function : FillShapesMap
395 //purpose  : auxiliary: fill a map by all compounds and their components
396 //=======================================================================
397
398 static void FillShapesMap (const TopoDS_Shape &S, TopTools_MapOfShape &map)
399 {
400   TopoDS_Shape S0 = S;
401   TopLoc_Location loc;
402   S0.Location ( loc );
403   map.Add ( S0 );
404   if ( S.ShapeType() != TopAbs_COMPOUND ) return;
405   for ( TopoDS_Iterator it(S); it.More(); it.Next() ) 
406     FillShapesMap ( it.Value(), map );
407 }
408
409
410 //=======================================================================
411 //function : Transfer
412 //purpose  : basic working method
413 //=======================================================================
414
415 Standard_Boolean STEPCAFControl_Reader::Transfer (STEPControl_Reader &reader,
416                                                   const Standard_Integer nroot,
417                                                   Handle(TDocStd_Document) &doc,
418                                                   TDF_LabelSequence &Lseq,
419                                                   const Standard_Boolean asOne)
420 {
421   reader.ClearShapes();
422   Standard_Integer i;
423   
424   // Read all shapes
425   Standard_Integer num = reader.NbRootsForTransfer();
426   if ( num <=0 ) return Standard_False;
427   if ( nroot ) {
428     if ( nroot > num ) return Standard_False;
429     reader.TransferOneRoot ( nroot );
430   }
431   else {
432     for ( i=1; i <= num; i++ ) reader.TransferOneRoot ( i );
433   }
434   num = reader.NbShapes();
435   if ( num <=0 ) return Standard_False;
436
437   // Fill a map of (top-level) shapes resulting from that transfer
438   // Only these shapes will be considered further
439   TopTools_MapOfShape ShapesMap, NewShapesMap;
440   for ( i=1; i <= num; i++ ) FillShapesMap ( reader.Shape(i), ShapesMap );
441   
442   // Collect information on shapes originating from SDRs
443   // this will be used to distinguish compounds representing assemblies
444   // from the ones representing hybrid models and shape sets
445   STEPCAFControl_DataMapOfShapePD ShapePDMap;
446   STEPCAFControl_DataMapOfPDExternFile PDFileMap;
447   Handle(Interface_InterfaceModel) Model = reader.Model();
448   Handle(Transfer_TransientProcess) TP = reader.WS()->TransferReader()->TransientProcess();
449   Standard_Integer nb = Model->NbEntities();
450
451   Handle(TColStd_HSequenceOfTransient) SeqPDS = new TColStd_HSequenceOfTransient;
452
453   for (i = 1; i <= nb; i ++) {
454     Handle(Standard_Transient) enti = Model->Value(i);
455     if(enti->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) {
456       // sequence for acceleration ReadMaterials
457       SeqPDS->Append(enti);
458     }
459     if ( enti->IsKind ( STANDARD_TYPE(StepBasic_ProductDefinition ) ) ) {
460       Handle(StepBasic_ProductDefinition) PD = 
461         Handle(StepBasic_ProductDefinition)::DownCast(enti);
462       Standard_Integer index = TP->MapIndex(PD);
463       if ( index >0 ) {
464         Handle(Transfer_Binder) binder = TP->MapItem (index);
465         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
466         if ( ! S.IsNull() && ShapesMap.Contains(S) ) {
467           NewShapesMap.Add(S);
468           ShapePDMap.Bind ( S, PD ); 
469           Handle(STEPCAFControl_ExternFile) EF;
470           PDFileMap.Bind ( PD, EF );
471         }
472       }
473     }
474     if ( enti->IsKind ( STANDARD_TYPE(StepShape_ShapeRepresentation) ) ) {
475       Standard_Integer index = TP->MapIndex(enti);
476       if ( index >0 ) {
477         Handle(Transfer_Binder) binder = TP->MapItem (index);
478         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
479         if ( ! S.IsNull() && ShapesMap.Contains(S) )
480           NewShapesMap.Add(S);
481       }
482     }
483   }
484
485   // get directory name of the main file
486   OSD_Path mainfile ( reader.WS()->LoadedFile() );
487   mainfile.SetName ( "" );
488   mainfile.SetExtension ( "" );
489   TCollection_AsciiString dpath;
490   mainfile.SystemName ( dpath );
491
492   // Load external references (only for relevant SDRs)
493   // and fill map SDR -> extern file
494   STEPConstruct_ExternRefs ExtRefs ( reader.WS() );
495   ExtRefs.LoadExternRefs();
496   for ( i=1; i <= ExtRefs.NbExternRefs(); i++ ) {
497     // check extern ref format
498     Handle(TCollection_HAsciiString) format = ExtRefs.Format(i);
499     if ( ! format.IsNull() ) {
500       static Handle(TCollection_HAsciiString) ap203 = new TCollection_HAsciiString ( "STEP AP203" );
501       static Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "STEP AP214" );
502       if ( ! format->IsSameString ( ap203, Standard_False ) && 
503            ! format->IsSameString ( ap214, Standard_False ) ) {
504 #ifdef OCCT_DEBUG
505         cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document is neither STEP AP203 nor AP214" << endl;
506 #else
507         continue;
508 #endif
509       }
510     }
511 #ifdef OCCT_DEBUG
512     else cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document format not defined" << endl;
513 #endif
514     
515     // get and check filename of the current extern ref
516     const Standard_CString filename = ExtRefs.FileName(i);
517
518 #ifdef OCCT_DEBUG
519     cout<<"filename="<<filename<<endl;
520 #endif
521
522     if ( ! filename || ! filename[0] ) {
523 #ifdef OCCT_DEBUG
524       cout << "Warning: STEPCAFControl_Reader::Transfer: Extern reference file name is empty" << endl;
525 #endif
526       continue; // not a valid extern ref
527     }
528
529     // compute true path to the extern file
530     TCollection_AsciiString fullname = OSD_Path::AbsolutePath ( dpath, filename );
531     if ( fullname.Length() <= 0 ) fullname = filename;
532
533 /*    
534     char fullname[1024];
535     char *mainfile = reader.WS()->LoadedFile();
536     if ( ! mainfile ) mainfile = "";
537     Standard_Integer slash = 0;
538     for ( Standard_Integer k=0; mainfile[k]; k++ )
539       if ( mainfile[k] == '/' ) slash = k;
540     strncpy ( fullname, mainfile, slash );
541     sprintf ( &fullname[slash], "%s%s", ( mainfile[0] ? "/" : "" ), filename );
542 */
543     
544     // get and check PD associated with the current extern ref
545     Handle(StepBasic_ProductDefinition) PD = ExtRefs.ProdDef(i);
546     if ( PD.IsNull() ) continue; // not a valid extern ref
547     if ( ! PDFileMap.IsBound ( PD ) ) continue; // this PD is not concerned by current transfer
548     
549     // read extern file (or use existing data) and record its data
550     Handle(STEPCAFControl_ExternFile) EF = 
551       ReadExternFile ( filename, fullname.ToCString(), doc );
552     PDFileMap.Bind ( PD, EF );
553   }
554   
555   // and insert them to the document
556   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
557   if ( STool.IsNull() ) return Standard_False;
558   XCAFDoc_DataMapOfShapeLabel map;
559   if ( asOne )
560     Lseq.Append ( AddShape ( reader.OneShape(), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
561   else {
562     for ( i=1; i <= num; i++ ) {
563       Lseq.Append ( AddShape ( reader.Shape(i), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
564     }
565   }
566   
567   // read colors
568   if ( GetColorMode() )
569     ReadColors ( reader.WS(), doc, PDFileMap, map );
570   
571   // read names
572   if ( GetNameMode() )
573     ReadNames ( reader.WS(), doc, PDFileMap, map );
574
575   // read validation props
576   if ( GetPropsMode() )
577     ReadValProps ( reader.WS(), doc, PDFileMap, map );
578
579   // read layers
580   if ( GetLayerMode() )
581     ReadLayers ( reader.WS(), doc );
582   
583   // read SHUO entities from STEP model
584   if ( GetSHUOMode() )
585     ReadSHUOs ( reader.WS(), doc, PDFileMap, map );
586
587   // read GDT entities from STEP model
588   if(GetGDTMode())
589     ReadGDTs(reader.WS(),doc);
590
591   // read Material entities from STEP model
592   if(GetMatMode())
593     ReadMaterials(reader.WS(),doc,SeqPDS);
594
595   // Expand resulting CAF structure for sub-shapes (optionally with their
596   // names) if requested
597   ExpandSubShapes(STool, map, ShapePDMap);
598
599   return Standard_True;
600 }
601
602 //=======================================================================
603 //function : AddShape
604 //purpose  : 
605 //=======================================================================
606
607 TDF_Label STEPCAFControl_Reader::AddShape (const TopoDS_Shape &S, 
608                                            const Handle(XCAFDoc_ShapeTool) &STool,
609                                            const TopTools_MapOfShape &NewShapesMap,
610                                            const STEPCAFControl_DataMapOfShapePD &ShapePDMap,
611                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
612                                            XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
613 {
614   // if shape has already been mapped, just return corresponding label
615   if ( ShapeLabelMap.IsBound ( S ) ) {
616     return ShapeLabelMap.Find ( S );
617   }
618   
619   // if shape is located, create instance
620   if ( ! S.Location().IsIdentity() ) {
621     TopoDS_Shape S0 = S;
622     TopLoc_Location loc;
623     S0.Location ( loc );
624     AddShape ( S0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
625     TDF_Label L = STool->AddShape ( S, Standard_False ); // should create reference
626     ShapeLabelMap.Bind ( S, L );
627     return L;
628   }
629   
630   // if shape is not compound, simple add it
631   if ( S.ShapeType() != TopAbs_COMPOUND ) {
632     TDF_Label L = STool->AddShape ( S, Standard_False );
633     ShapeLabelMap.Bind ( S, L );
634     return L;
635   }
636   
637   // for compounds, compute number of subshapes and check whether this is assembly
638   Standard_Boolean isAssembly = Standard_False;
639   Standard_Integer nbComponents = 0;
640   TopoDS_Iterator it;
641   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
642     TopoDS_Shape Sub0 = it.Value();
643     TopLoc_Location loc;
644     Sub0.Location ( loc );
645     if ( NewShapesMap.Contains ( Sub0 ) ) isAssembly = Standard_True;
646   }
647
648 //  if(nbComponents>0) isAssembly = Standard_True;
649   
650   // check whether it has associated external ref
651   TColStd_SequenceOfHAsciiString SHAS;
652   if ( ShapePDMap.IsBound ( S ) && PDFileMap.IsBound ( ShapePDMap.Find(S) ) ) {
653     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( ShapePDMap.Find(S) );
654     if ( ! EF.IsNull() ) {
655       // (store information on extern refs in the document)
656       SHAS.Append(EF->GetName());
657       // if yes, just return corresponding label
658       if ( ! EF->GetLabel().IsNull() ) {
659         // but if components >0, ignore extern ref!
660         if ( nbComponents <=0 ) {
661           ShapeLabelMap.Bind ( S, EF->GetLabel() );
662           STool->SetExternRefs(EF->GetLabel(),SHAS);
663           return EF->GetLabel();
664         }
665       }
666 #ifdef OCCT_DEBUG
667       if ( ! EF->GetLabel().IsNull() )
668         cout << "Warning: STEPCAFControl_Reader::AddShape: Non-empty shape with external ref; ref is ignored" << endl;
669       else if ( nbComponents <=0 ) 
670         cout << "Warning: STEPCAFControl_Reader::AddShape: Result of reading extern ref is Null" << endl;
671 #endif
672     }
673   }
674   
675   // add compound either as a whole,
676   if ( ! isAssembly ) {
677     TDF_Label L = STool->AddShape ( S, Standard_False );
678     if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
679     ShapeLabelMap.Bind ( S, L );
680     return L;
681   }
682   
683   // or as assembly, component-by-component
684   TDF_Label L = STool->NewShape();
685   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
686     TopoDS_Shape Sub0 = it.Value();
687     TopLoc_Location loc;
688     Sub0.Location ( loc );
689     TDF_Label subL = AddShape ( Sub0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
690     if ( ! subL.IsNull() ) {
691       STool->AddComponent ( L, subL, it.Value().Location() );
692     }
693   }
694   if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
695   ShapeLabelMap.Bind ( S, L );
696   //STool->SetShape ( L, S ); // it is necessary for assemblies OCC1747 // commemted by skl for OCC2941
697
698   return L;
699 }
700
701 //=======================================================================
702 //function : ReadExternFile
703 //purpose  : 
704 //=======================================================================
705
706 Handle(STEPCAFControl_ExternFile) STEPCAFControl_Reader::ReadExternFile (const Standard_CString file, 
707                                                                          const Standard_CString fullname, 
708                                                                          Handle(TDocStd_Document)& doc) 
709 {
710   // if the file is already read, associate it with SDR
711   if ( myFiles->HasItem ( file, Standard_True ) ) {
712     return myFiles->Item ( file );
713   }
714
715 #ifdef OCCT_DEBUG
716   cout << "Reading extern file: " << fullname << endl;
717 #endif
718  
719   // create new WorkSession and Reader
720   Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
721   newWS->SelectNorm ( "STEP" );
722   STEPControl_Reader sr ( newWS, Standard_False );
723   
724   // start to fill the resulting ExternFile structure
725   Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
726   EF->SetWS ( newWS );
727   EF->SetName ( new TCollection_HAsciiString ( file ) );
728   
729   // read file
730   EF->SetLoadStatus ( sr.ReadFile ( fullname ) );
731   
732   // transfer in single-result mode
733   if ( EF->GetLoadStatus() == IFSelect_RetDone ) {
734     TDF_LabelSequence labels;
735     EF->SetTransferStatus ( Transfer ( sr, 0, doc, labels, Standard_True ) );
736     if ( labels.Length() >0 ) EF->SetLabel ( labels.Value(1) );
737   }
738   
739   // add read file to dictionary
740   myFiles->SetItem ( file, EF );
741   
742   return EF;
743 }
744
745
746 //=======================================================================
747 //function : SetColorToSubshape
748 //purpose  : auxilary
749 //=======================================================================
750 static void SetColorToSubshape(const Handle(XCAFDoc_ColorTool) & CTool,
751                                const TopoDS_Shape & S,
752                                const Quantity_Color& col,
753                                const XCAFDoc_ColorType type)
754 {
755   for (TopoDS_Iterator it(S); it.More(); it.Next())
756     if (! CTool->SetColor( it.Value(), col, type)) break;
757 }
758
759
760 //=======================================================================
761 //function : findStyledSR
762 //purpose  : auxilary
763 //=======================================================================
764 static void findStyledSR (const Handle(StepVisual_StyledItem) &style,
765                           Handle(StepShape_ShapeRepresentation)& aSR)
766 {
767   // search Shape Represenatation for component styled item
768   for ( Standard_Integer j=1; j <= style->NbStyles(); j++ ) {
769     Handle(StepVisual_PresentationStyleByContext) PSA = 
770       Handle(StepVisual_PresentationStyleByContext)::DownCast(style->StylesValue ( j ));
771     if ( PSA.IsNull() )
772       continue;
773     StepVisual_StyleContextSelect aStyleCntxSlct = PSA->StyleContext();
774     Handle(StepShape_ShapeRepresentation) aCurrentSR = 
775       Handle(StepShape_ShapeRepresentation)::DownCast(aStyleCntxSlct.Representation());
776     if ( aCurrentSR.IsNull() )
777       continue;
778     aSR = aCurrentSR;
779       break;
780   }
781 }
782
783
784 //=======================================================================
785 //function : ReadColors
786 //purpose  : 
787 //=======================================================================
788
789 Standard_Boolean STEPCAFControl_Reader::ReadColors (const Handle(XSControl_WorkSession) &WS,
790                                                     Handle(TDocStd_Document)& Doc,
791                                                     const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
792                                                     const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
793 {
794   STEPConstruct_Styles Styles ( WS );
795   if ( ! Styles.LoadStyles() ) {
796 #ifdef OCCT_DEBUG
797     cout << "Warning: no styles are found in the model" << endl;
798 #endif
799     return Standard_False;
800   }
801   // searching for invisible items in the model
802   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
803   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
804   
805   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
806   if ( CTool.IsNull() ) return Standard_False;
807
808   // parse and search for color attributes
809   Standard_Integer nb = Styles.NbStyles();
810   for ( Standard_Integer i=1; i <= nb; i++ ) {
811     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
812     if ( style.IsNull() ) continue;
813     
814     Standard_Boolean IsVisible = Standard_True;
815     // check the visibility of styled item.
816     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
817       if ( style != aHSeqOfInvisStyle->Value( si ) )
818         continue;
819       // found that current style is invisible.
820       IsVisible = Standard_False;
821       break;
822     }
823
824     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
825     // check if it is component style
826     Standard_Boolean IsComponent = Standard_False;
827     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
828       continue;
829     
830     // find shape
831     TopoDS_Shape S = STEPConstruct::FindShape ( Styles.TransientProcess(), style->Item() );
832     Standard_Boolean isSkipSHUOstyle = Standard_False;
833     // take shape with real location.
834     while ( IsComponent ) {
835       // take SR of NAUO
836       Handle(StepShape_ShapeRepresentation) aSR;
837       findStyledSR( style, aSR );
838       // search for SR along model
839       if (aSR.IsNull())
840         break;
841 //       Handle(Interface_InterfaceModel) Model = WS->Model();
842       Handle(XSControl_TransferReader) TR = WS->TransferReader();
843       Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
844       Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
845       Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
846       for (subs.Start(); subs.More(); subs.Next()) {
847         aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
848         if ( aSDR.IsNull() )
849           continue;
850         StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
851         Handle(StepRepr_ProductDefinitionShape) PDS = 
852           Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
853         if ( PDS.IsNull() )
854           continue;
855         StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
856         
857         Handle(StepRepr_AssemblyComponentUsage) ACU = 
858           Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
859         // PTV 10.02.2003 skip styled item that refer to SHUO
860         if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
861           isSkipSHUOstyle = Standard_True;
862           break;
863         }
864         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
865           Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
866         if ( NAUO.IsNull() )
867           continue;
868         
869         TopoDS_Shape aSh;
870         // PTV 10.02.2003 to find component of assembly CORRECTLY
871         STEPConstruct_Tool Tool( WS );
872         TDF_Label aShLab = FindInstance ( NAUO, CTool->ShapeTool(), Tool, PDFileMap, ShapeLabelMap );
873         aSh = CTool->ShapeTool()->GetShape(aShLab);
874 //         Handle(Transfer_Binder) binder = TP->Find(NAUO);
875 //         if ( binder.IsNull() || ! binder->HasResult() )
876 //           continue;
877 //         aSh = TransferBRep::ShapeResult ( TP, binder );
878         if (!aSh.IsNull()) {
879           S = aSh;
880           break;
881         }
882       }
883       break;
884     }
885     if (isSkipSHUOstyle)
886       continue; // skip styled item which refer to SHUO
887     
888     if ( S.IsNull() )
889       continue;
890     
891     if ( ! SurfCol.IsNull() ) {
892       Quantity_Color col;
893       Styles.DecodeColor ( SurfCol, col );
894       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorSurf ))
895         SetColorToSubshape( CTool, S, col, XCAFDoc_ColorSurf );
896     }
897     if ( ! BoundCol.IsNull() ) {
898       Quantity_Color col;
899       Styles.DecodeColor ( BoundCol, col );
900       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
901         SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
902     }
903     if ( ! CurveCol.IsNull() ) {
904       Quantity_Color col;
905       Styles.DecodeColor ( CurveCol, col );
906       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
907         SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
908     }
909     if ( !IsVisible ) {
910       // sets the invisibility for shape.
911       TDF_Label aInvL;
912       if ( CTool->ShapeTool()->Search( S, aInvL ) )
913         CTool->SetVisibility( aInvL, Standard_False );
914     }
915   }
916   CTool->ReverseChainsOfTreeNodes();
917   return Standard_True;
918 }
919
920 //=======================================================================
921 //function : GetLabelFromPD
922 //purpose  : 
923 //=======================================================================
924
925 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
926                                  const Handle(XCAFDoc_ShapeTool) &STool,
927                                  const Handle(Transfer_TransientProcess) &TP,
928                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
929                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
930 {
931   TDF_Label L;
932   if ( PDFileMap.IsBound ( PD ) ) {
933     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
934     if ( ! EF.IsNull() ) {
935       L = EF->GetLabel();
936       if ( ! L.IsNull() ) return L;
937     }
938   }
939
940   TopoDS_Shape S;
941   Handle(Transfer_Binder) binder = TP->Find(PD);
942   if ( binder.IsNull() || ! binder->HasResult() ) return L;
943   S = TransferBRep::ShapeResult ( TP, binder );
944   if ( S.IsNull() ) return L;
945
946   if ( S.IsNull() ) return L;
947   if ( ShapeLabelMap.IsBound ( S ) )
948     L = ShapeLabelMap.Find ( S );
949   if ( L.IsNull() )
950     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
951   return L;
952 }
953
954 //=======================================================================
955 //function : FindInstance
956 //purpose  : 
957 //=======================================================================
958
959 TDF_Label STEPCAFControl_Reader::FindInstance (const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
960                                                const Handle(XCAFDoc_ShapeTool) &STool,
961                                                const STEPConstruct_Tool &Tool,
962                                                const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
963                                                const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
964 {
965   TDF_Label L;
966   
967   // get shape resulting from CDSR (in fact, only location is interesting)
968   Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
969   Handle(Transfer_Binder) binder = TP->Find(NAUO);
970   if ( binder.IsNull() || ! binder->HasResult() ) {
971 #ifdef OCCT_DEBUG
972     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
973 #endif
974     return L;
975   }
976   
977   TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
978   if ( S.IsNull() ) {
979 #ifdef OCCT_DEBUG
980     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
981 #endif
982     return L;
983   }
984
985   // find component`s original label
986   Handle(StepBasic_ProductDefinition) PD = NAUO->RelatedProductDefinition();
987   if ( PD.IsNull() ) return L;
988   TDF_Label Lref = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
989   if ( Lref.IsNull() ) return L;
990   
991   // find main shape (assembly) label
992   PD.Nullify();
993   PD = NAUO->RelatingProductDefinition();
994   if ( PD.IsNull() ) return L;
995   TDF_Label L0 = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
996   if ( L0.IsNull() ) return L;
997   
998   // if CDSR and NAUO are reversed, swap labels
999   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1000   Interface_EntityIterator subs1 = Tool.Graph().Sharings(NAUO);
1001   for (subs1.Start(); subs1.More(); subs1.Next()) {
1002     Handle(StepRepr_ProductDefinitionShape) PDS = 
1003       Handle(StepRepr_ProductDefinitionShape)::DownCast(subs1.Value());
1004     if(PDS.IsNull()) continue;
1005     Interface_EntityIterator subs2 = Tool.Graph().Sharings(PDS);
1006     for (subs2.Start(); subs2.More(); subs2.Next()) {
1007       Handle(StepShape_ContextDependentShapeRepresentation) CDSRtmp = 
1008         Handle(StepShape_ContextDependentShapeRepresentation)::DownCast(subs2.Value());
1009       if (CDSRtmp.IsNull()) continue;
1010       CDSR = CDSRtmp;
1011     }
1012   }
1013   if (CDSR.IsNull()) return L;
1014 //  if ( STEPConstruct_Assembly::CheckSRRReversesNAUO ( Tool.Model(), CDSR ) ) {
1015 //    TDF_Label Lsw = L0; L0 = Lref; Lref = Lsw;
1016 //  }
1017   
1018   // iterate on components to find proper one
1019   TDF_LabelSequence seq;
1020   XCAFDoc_ShapeTool::GetComponents ( L0, seq );
1021   for ( Standard_Integer k=1; L.IsNull() && k <= seq.Length(); k++ ) {
1022     TDF_Label Lcomp = seq(k), Lref2;
1023     if ( XCAFDoc_ShapeTool::GetReferredShape ( Lcomp, Lref2 ) && 
1024         Lref2 == Lref &&
1025         S.Location() == XCAFDoc_ShapeTool::GetLocation ( Lcomp ) ) 
1026       L = Lcomp;
1027   }
1028   
1029   return L;
1030 }
1031
1032 //=======================================================================
1033 //function : ReadNames
1034 //purpose  : 
1035 //=======================================================================
1036
1037 Standard_Boolean STEPCAFControl_Reader::ReadNames (const Handle(XSControl_WorkSession) &WS,
1038                                                    Handle(TDocStd_Document)& Doc,
1039                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1040                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1041 {
1042   // get starting data
1043   Handle(Interface_InterfaceModel) Model = WS->Model();
1044   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1045   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1046   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1047   if ( STool.IsNull() ) return Standard_False;
1048   STEPConstruct_Tool Tool ( WS );
1049
1050   // iterate on model to find all SDRs and CDSRs
1051   Standard_Integer nb = Model->NbEntities();
1052   Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
1053   Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
1054   Handle(TCollection_HAsciiString) name;
1055   TDF_Label L;
1056   for (Standard_Integer i = 1; i <= nb; i++) {
1057     Handle(Standard_Transient) enti = Model->Value(i);
1058
1059     // get description of NAUO
1060     if ( enti->DynamicType() == tNAUO ) {
1061       L.Nullify();
1062       Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
1063         Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
1064       if(NAUO.IsNull()) continue;
1065       Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
1066       for (subs.Start(); subs.More(); subs.Next()) {
1067         Handle(StepRepr_ProductDefinitionShape) PDS = 
1068           Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1069         if(PDS.IsNull()) continue;
1070         Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
1071         if ( PDR.IsNull() ) continue;
1072         if ( PDR->HasDescription() && 
1073             PDR->Description()->Length() >0 ) name = PDR->Description();
1074         else if ( !PDR->Name().IsNull() && PDR->Name()->Length() >0 ) name = PDR->Name();
1075         else if ( !PDR->Id().IsNull()) name = PDR->Id();
1076         else name = new TCollection_HAsciiString;
1077       }
1078       // find proper label
1079       L = FindInstance ( NAUO, STool, Tool, PDFileMap, ShapeLabelMap );
1080       if ( L.IsNull() ) continue;
1081       TCollection_ExtendedString str ( name->String() );
1082       TDataStd_Name::Set ( L, str );
1083     }
1084
1085     // for PD get name of associated product
1086     if ( enti->DynamicType() == tPD ) {
1087       L.Nullify();
1088       Handle(StepBasic_ProductDefinition) PD = 
1089         Handle(StepBasic_ProductDefinition)::DownCast(enti);
1090       if(PD.IsNull()) continue;
1091       Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
1092       if(!Prod->Name().IsNull() && Prod->Name()->UsefullLength()>0) name = Prod->Name();
1093       else if (!Prod->Id().IsNull()) name = Prod->Id();
1094       else name = new TCollection_HAsciiString;
1095       L = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1096       if ( L.IsNull() ) continue;
1097       TCollection_ExtendedString str ( name->String() );
1098       TDataStd_Name::Set ( L, str );
1099     }
1100     // set a name to the document
1101     //TCollection_ExtendedString str ( name->String() );
1102     //TDataStd_Name::Set ( L, str );
1103   }
1104
1105   return Standard_True;
1106 }
1107
1108 //=======================================================================
1109 //function : GetLabelFromPD
1110 //purpose  : 
1111 //=======================================================================
1112
1113 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1114                                  const Handle(XCAFDoc_ShapeTool) &STool,
1115                                  const STEPConstruct_ValidationProps &Props,
1116                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1117                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1118 {
1119   TDF_Label L;
1120   if ( PDFileMap.IsBound ( PD ) ) {
1121     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1122     if ( ! EF.IsNull() ) {
1123       L = EF->GetLabel();
1124       if ( ! L.IsNull() ) return L;
1125     }
1126   }
1127   TopoDS_Shape S = Props.GetPropShape ( PD );
1128   if ( S.IsNull() ) return L;
1129   if ( ShapeLabelMap.IsBound ( S ) )
1130     L = ShapeLabelMap.Find ( S );
1131   if ( L.IsNull() )
1132     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1133   return L;
1134 }
1135
1136 //=======================================================================
1137 //function : ReadValProps
1138 //purpose  : 
1139 //=======================================================================
1140
1141 Standard_Boolean STEPCAFControl_Reader::ReadValProps (const Handle(XSControl_WorkSession) &WS,
1142                                                       Handle(TDocStd_Document)& Doc,
1143                                                       const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1144                                                       const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1145 {
1146   // get starting data
1147   Handle(Interface_InterfaceModel) Model = WS->Model();
1148   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1149   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1150   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1151   if ( STool.IsNull() ) return Standard_False;
1152
1153   // load props from the STEP model
1154   TColStd_SequenceOfTransient props;
1155   STEPConstruct_ValidationProps Props ( WS );
1156   if ( ! Props.LoadProps ( props ) ) {
1157 #ifdef OCCT_DEBUG
1158     cout << "Warning: no validation props found in the model" << endl;
1159 #endif
1160     return Standard_False;
1161   }
1162
1163   // interpret props one by one
1164   for (Standard_Integer i = 1; i <= props.Length(); i ++) {
1165     Handle(StepRepr_PropertyDefinitionRepresentation) PDR = 
1166       Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast ( props.Value(i) );
1167     if ( PDR.IsNull() ) continue;
1168
1169     TDF_Label L;
1170
1171     Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
1172     Interface_EntityIterator subs = Props.Graph().Shareds(PD);
1173     for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
1174       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)) ) {
1175         Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1176         if(PDS.IsNull()) continue;
1177         // find corresponding NAUO
1178         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
1179         Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
1180         for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
1181           if ( subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)) ) 
1182             NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
1183         }
1184         if ( !NAUO.IsNull() ) {
1185           L = FindInstance ( NAUO, STool, WS, PDFileMap, ShapeLabelMap );
1186           if ( L.IsNull() ) continue;
1187         }
1188         else {
1189           // find corresponding ProductDefinition:
1190           Handle(StepBasic_ProductDefinition) ProdDef;
1191           Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
1192           for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
1193             if ( subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)) ) 
1194               ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
1195           }
1196           if ( ProdDef.IsNull() ) continue;
1197           L = GetLabelFromPD ( ProdDef, STool, Props, PDFileMap, ShapeLabelMap );
1198         }
1199       }
1200
1201       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)) ) {
1202         Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
1203         if(SA.IsNull()) continue;
1204         // find ShapeRepresentation
1205         Handle(StepShape_ShapeRepresentation) SR;
1206         Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
1207         for(subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
1208           Handle(StepRepr_PropertyDefinition) PropD1 = 
1209             Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
1210           if(PropD1.IsNull()) continue;
1211           Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
1212           for(subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
1213             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1214               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
1215             if(SDR.IsNull()) continue;
1216             SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1217           }
1218         }
1219         if(SR.IsNull()) continue;
1220         Handle(Transfer_Binder) binder;
1221         for(Standard_Integer ir=1; ir<=SR->NbItems() && binder.IsNull(); ir++) {
1222           if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
1223             Handle(StepShape_SolidModel) SM = 
1224               Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
1225             binder = TP->Find(SM);
1226           }
1227           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1228             Handle(StepShape_ShellBasedSurfaceModel) SBSM =
1229               Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
1230             binder = TP->Find(SBSM);
1231           }
1232           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1233             Handle(StepShape_GeometricSet) GS =
1234               Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
1235             binder = TP->Find(GS);
1236           }
1237         }
1238         if ( binder.IsNull() || ! binder->HasResult() ) continue;
1239         TopoDS_Shape S;
1240         S = TransferBRep::ShapeResult ( TP, binder );
1241         if(S.IsNull()) continue;
1242         if ( ShapeLabelMap.IsBound ( S ) )
1243           L = ShapeLabelMap.Find ( S );
1244         if ( L.IsNull() )
1245           STool->Search ( S, L, Standard_True, Standard_True, Standard_True );
1246       }
1247     }
1248
1249     if(L.IsNull()) continue;
1250       
1251     // decode validation properties
1252     Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
1253     for ( Standard_Integer j=1; j <= rep->NbItems(); j++ ) {
1254       Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
1255       Standard_Boolean isArea;
1256       Standard_Real val;
1257       gp_Pnt pos;
1258       if ( Props.GetPropReal ( ent, val, isArea ) ) {
1259         if ( isArea ) XCAFDoc_Area::Set ( L, val );
1260         else XCAFDoc_Volume::Set ( L, val );
1261       }
1262       else if ( Props.GetPropPnt ( ent, rep->ContextOfItems(), pos ) ) {
1263         XCAFDoc_Centroid::Set ( L, pos );
1264       }
1265     }
1266   }
1267   return Standard_True;
1268 }
1269
1270 //=======================================================================
1271 //function : ReadLayers
1272 //purpose  : 
1273 //=======================================================================
1274
1275 Standard_Boolean STEPCAFControl_Reader::ReadLayers (const Handle(XSControl_WorkSession) &WS,
1276                                                     Handle(TDocStd_Document)& Doc) const
1277 {
1278   Handle(Interface_InterfaceModel) Model = WS->Model();
1279   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1280   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1281   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1282   if ( STool.IsNull() ) return Standard_False;
1283   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( Doc->Main() );
1284   if ( LTool.IsNull() ) return Standard_False;
1285   
1286   Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
1287   Standard_Integer nb = Model->NbEntities();
1288   Handle(TCollection_HAsciiString) name;
1289   
1290   for (Standard_Integer i = 1; i <= nb; i ++) {
1291     Handle(Standard_Transient) enti = Model->Value(i);
1292     if ( ! enti->IsKind ( tSVPLA ) ) continue;
1293     Handle(StepVisual_PresentationLayerAssignment) SVPLA = 
1294       Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
1295     
1296     Handle(TCollection_HAsciiString) descr = SVPLA->Description();
1297     Handle(TCollection_HAsciiString) hName = SVPLA->Name();
1298     TCollection_ExtendedString aLayerName ( hName->String() );
1299      
1300     // find a target shape and its label in the document
1301     for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++ ) {
1302       StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
1303       Handle(Transfer_Binder) binder = TP->Find( LI.Value() );
1304       if ( binder.IsNull() || ! binder->HasResult() ) continue;
1305       
1306       TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1307       if ( S.IsNull() ) continue;
1308         
1309       TDF_Label shL;
1310       if ( ! STool->Search ( S, shL, Standard_True, Standard_True, Standard_True ) ) continue;
1311       LTool->SetLayer ( shL, aLayerName );
1312     }
1313     
1314     // check invisibility
1315     Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
1316     for (subs.Start(); subs.More(); subs.Next()) {
1317       if ( ! subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility)) ) continue;
1318 #ifdef OCCT_DEBUG
1319       cout<< "\tLayer \"" << aLayerName << "\" is invisible"<<endl;
1320 #endif
1321       //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
1322       TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
1323       Handle(TDataStd_UAttribute) aUAttr;
1324       aUAttr->Set( InvLayerLab, XCAFDoc::InvisibleGUID() );
1325     }
1326   }
1327   return Standard_True;
1328 }
1329
1330 //=======================================================================
1331 //function : ReadSHUOs
1332 //purpose  : 
1333 //=======================================================================
1334
1335 static Standard_Boolean findNextSHUOlevel (const Handle(XSControl_WorkSession) &WS,
1336                                            const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1337                                            const Handle(XCAFDoc_ShapeTool)& STool,
1338                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1339                                            const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1340                                            TDF_LabelSequence& aLabels)
1341 {
1342   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1343   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1344   for (subs.Start(); subs.More(); subs.Next()) {
1345     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1346       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1347       break;
1348     }
1349   }
1350   if (subSHUO.IsNull())
1351     return Standard_False;
1352   
1353   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO =
1354     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subSHUO->NextUsage());
1355   if (NUNAUO.IsNull())
1356     return Standard_False;
1357 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1358 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1359 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1360 //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1361 //   if ( binder.IsNull() || ! binder->HasResult() )
1362 //     return Standard_False;
1363 //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1364   // get label of NAUO next level
1365   TDF_Label NULab;
1366   STEPConstruct_Tool Tool( WS );
1367   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1368 //   STool->Search(NUSh, NUlab);
1369   if (NULab.IsNull())
1370     return Standard_False;
1371   aLabels.Append( NULab );
1372   // and check by recurse.
1373   findNextSHUOlevel( WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels );
1374   return Standard_True;
1375 }
1376
1377
1378 //=======================================================================
1379 //function : setSHUOintoDoc
1380 //purpose  : auxilary
1381 //=======================================================================
1382 static TDF_Label setSHUOintoDoc (const Handle(XSControl_WorkSession) &WS,
1383                                  const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1384                                  const Handle(XCAFDoc_ShapeTool)& STool,
1385                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1386                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1387 {
1388   TDF_Label aMainLabel;
1389   // get upper usage NAUO from SHUO.
1390   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1391     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1392   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO =
1393     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->NextUsage());
1394   if ( UUNAUO.IsNull() || NUNAUO.IsNull() ) {
1395 #ifdef OCCT_DEBUG
1396     cout << "Warning: " << __FILE__ <<": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
1397 #endif
1398     return aMainLabel;
1399   }
1400 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1401 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1402 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1403 //   TopoDS_Shape UUSh, NUSh;
1404 //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1405 //   if ( binder.IsNull() || ! binder->HasResult() )
1406 //     return aMainLabel;
1407 //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1408 //   binder = TP->Find(NUNAUO);
1409 //   if ( binder.IsNull() || ! binder->HasResult() )
1410 //     return aMainLabel;
1411 //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1412
1413   // get first labels for first SHUO attribute
1414   TDF_Label UULab, NULab;
1415   STEPConstruct_Tool Tool( WS );
1416   UULab = STEPCAFControl_Reader::FindInstance ( UUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1417   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1418   
1419 //   STool->Search(UUSh, UULab);
1420 //   STool->Search(NUSh, NULab);
1421   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1422   //create sequence fo labels to set SHUO structure into the document
1423   TDF_LabelSequence ShuoLabels;
1424   ShuoLabels.Append( UULab );
1425   ShuoLabels.Append( NULab );
1426   // add all other labels of sub SHUO entities
1427   findNextSHUOlevel( WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels );
1428   // last accord for SHUO
1429   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1430   if ( STool->SetSHUO( ShuoLabels, anSHUOAttr ) )
1431     aMainLabel = anSHUOAttr->Label();
1432   
1433   return aMainLabel;
1434 }
1435
1436
1437 //=======================================================================
1438 //function : ReadSHUOs
1439 //purpose  : 
1440 //=======================================================================
1441
1442 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs (const Handle(XSControl_WorkSession) &WS,
1443                                                    Handle(TDocStd_Document)& Doc,
1444                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1445                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1446 {
1447   // the big part code duplication from ReadColors.
1448   // It is possible to share this code functionality, just to decide how ???
1449   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
1450   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1451   
1452   STEPConstruct_Styles Styles ( WS );
1453   if ( ! Styles.LoadStyles() ) {
1454 #ifdef OCCT_DEBUG
1455     cout << "Warning: no styles are found in the model" << endl;
1456 #endif
1457     return Standard_False;
1458   }
1459   // searching for invisible items in the model
1460   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1461   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
1462   // parse and search for color attributes
1463   Standard_Integer nb = Styles.NbStyles();
1464   for ( Standard_Integer i=1; i <= nb; i++ ) {
1465     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
1466     if ( style.IsNull() ) continue;
1467     
1468     Standard_Boolean IsVisible = Standard_True;
1469     // check the visibility of styled item.
1470     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
1471       if ( style != aHSeqOfInvisStyle->Value( si ) )
1472         continue;
1473       // found that current style is invisible.
1474 #ifdef OCCT_DEBUG
1475       cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
1476 #endif
1477       IsVisible = Standard_False;
1478       break;
1479     }
1480
1481     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
1482     // check if it is component style
1483     Standard_Boolean IsComponent = Standard_False;
1484     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
1485       continue;
1486     if (!IsComponent)
1487       continue;
1488     Handle(StepShape_ShapeRepresentation) aSR;
1489     findStyledSR( style, aSR );
1490     // search for SR along model
1491     if ( aSR.IsNull() )
1492       continue;
1493     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
1494     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1495     for (subs.Start(); subs.More(); subs.Next()) {
1496       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1497       if ( aSDR.IsNull() )
1498         continue;
1499       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1500       Handle(StepRepr_ProductDefinitionShape) PDS = 
1501         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1502       if ( PDS.IsNull() )
1503         continue;
1504       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1505       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1506         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1507       if ( SHUO.IsNull() )
1508         continue;
1509       
1510       // set the SHUO structure to the document
1511       TDF_Label aLabelForStyle = setSHUOintoDoc( WS, SHUO, STool, PDFileMap, ShapeLabelMap );
1512       if ( aLabelForStyle.IsNull() ) {
1513 #ifdef OCCT_DEBUG
1514         cout << "Warning: " << __FILE__ <<": coudnot create SHUO structure in the document" << endl;
1515 #endif
1516         continue;
1517       }
1518       // now set the style to the SHUO main label.
1519       if ( ! SurfCol.IsNull() ) {
1520         Quantity_Color col;
1521         Styles.DecodeColor ( SurfCol, col );
1522         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorSurf );
1523       }
1524       if ( ! BoundCol.IsNull() ) {
1525         Quantity_Color col;
1526         Styles.DecodeColor ( BoundCol, col );
1527         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1528       }
1529       if ( ! CurveCol.IsNull() ) {
1530         Quantity_Color col;
1531         Styles.DecodeColor ( CurveCol, col );
1532         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1533       }
1534       if ( !IsVisible )
1535         // sets the invisibility for shape.
1536         CTool->SetVisibility( aLabelForStyle, Standard_False );
1537       
1538     } // end search SHUO by SDR
1539   } // end iterates on styles
1540       
1541   return Standard_True;
1542 }
1543
1544
1545 //=======================================================================
1546 //function : GetLengthConversionFactor
1547 //purpose  : 
1548 //=======================================================================
1549 static Standard_Boolean GetLengthConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1550                                                   Standard_Real& afact)
1551 {
1552   afact=1.;
1553   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit)) ) return Standard_False;
1554   Handle(StepBasic_ConversionBasedUnitAndLengthUnit) CBULU =
1555     Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(NU);
1556   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1557   afact = MWUCBU->ValueComponent();
1558   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1559   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1560     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1561     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1562       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1563       if(SU->Name()==StepBasic_sunMetre) {
1564         if(SU->HasPrefix()) 
1565           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1566         // convert m to mm
1567         afact *= 1000.;
1568       }
1569     }
1570   }
1571   return Standard_True;
1572 }
1573
1574
1575 //=======================================================================
1576 //function : GetMassConversionFactor
1577 //purpose  : 
1578 //=======================================================================
1579 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1580                                                 Standard_Real& afact)
1581 {
1582   afact=1.;
1583   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit)) ) return Standard_False;
1584   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1585     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1586   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1587   afact = MWUCBU->ValueComponent();
1588   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1589   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1590     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1591     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1592       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1593       if(SU->Name()==StepBasic_sunGram) {
1594         if(SU->HasPrefix())
1595           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1596       }
1597     }
1598   }
1599   return Standard_True;
1600 }
1601
1602
1603 //=======================================================================
1604 //function : ReadDatums
1605 //purpose  : auxilary
1606 //=======================================================================
1607 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
1608                                    const Handle(XCAFDoc_DimTolTool) &DGTTool,
1609                                    const Interface_Graph &graph,
1610                                    Handle(Transfer_TransientProcess) &TP,
1611                                    const TDF_Label TolerL,
1612                                    const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
1613 {
1614   if(GTWDR.IsNull()) return Standard_False;
1615   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
1616   if(HADR.IsNull()) return Standard_False;
1617   for(Standard_Integer idr=1; idr<=HADR->Length(); idr++) {
1618     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
1619     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
1620     if(aDatum.IsNull()) continue;
1621     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
1622     for(subs4.Start(); subs4.More(); subs4.Next()) {
1623       Handle(StepRepr_ShapeAspectRelationship) SAR = 
1624         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
1625       if(SAR.IsNull()) continue;
1626       Handle(StepDimTol_DatumFeature) DF = 
1627         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
1628       if(DF.IsNull()) continue;
1629       Interface_EntityIterator subs5 = graph.Sharings(DF);
1630       Handle(StepRepr_PropertyDefinition) PropDef;
1631       for(subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
1632         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
1633       }
1634       if(PropDef.IsNull()) continue;
1635       Handle(StepShape_AdvancedFace) AF;
1636       subs5 = graph.Sharings(PropDef);
1637       for(subs5.Start(); subs5.More(); subs5.Next()) {
1638         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
1639           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
1640         if(!SDR.IsNull()) {
1641           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
1642           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
1643             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
1644             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
1645           }
1646         }
1647       }
1648       if(AF.IsNull()) return Standard_False;
1649       Standard_Integer index = TP->MapIndex(AF);
1650       TopoDS_Shape aSh;
1651       if(index >0) {
1652         Handle(Transfer_Binder) binder = TP->MapItem(index);
1653         aSh = TransferBRep::ShapeResult(binder);
1654       }
1655       if(aSh.IsNull()) continue; 
1656       TDF_Label shL;
1657       if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
1658       DGTTool->SetDatum(shL,TolerL,PropDef->Name(),PropDef->Description(),aDatum->Identification());
1659     }
1660   }
1661   return Standard_True;
1662 }
1663
1664
1665 //=======================================================================
1666 //function : ReadGDTs
1667 //purpose  : 
1668 //=======================================================================
1669
1670 Standard_Boolean STEPCAFControl_Reader::ReadGDTs(const Handle(XSControl_WorkSession) &WS,
1671                                                  Handle(TDocStd_Document)& Doc) const
1672 {
1673   Handle(Interface_InterfaceModel) Model = WS->Model();
1674   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1675   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1676   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1677   Handle(XCAFDoc_DimTolTool) DGTTool = XCAFDoc_DocumentTool::DimTolTool( Doc->Main() );
1678   if ( DGTTool.IsNull() ) return Standard_False;
1679   
1680   Standard_Integer nb = Model->NbEntities();
1681   const Interface_Graph& graph = TP->Graph();
1682   for(Standard_Integer i=1; i<=nb; i++) {
1683     Handle(Standard_Transient) ent = Model->Value(i);
1684     if(ent->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))) {
1685       Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(ent);
1686       // find RepresentationItem for current ShapeAspect
1687       Handle(StepRepr_RepresentationItem) RI;
1688       Handle(StepRepr_PropertyDefinition) PropD;
1689       Interface_EntityIterator subs3 = graph.Sharings(SA);
1690       for(subs3.Start(); subs3.More() && PropD.IsNull(); subs3.Next()) {
1691         PropD = Handle(StepRepr_PropertyDefinition)::DownCast(subs3.Value());
1692       }
1693       if(PropD.IsNull()) continue;
1694       Interface_EntityIterator subs4 = graph.Sharings(PropD);
1695       for(subs4.Start(); subs4.More(); subs4.Next()) {
1696         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
1697           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
1698         if(!SDR.IsNull()) {
1699           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
1700           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
1701             RI = Repr->ItemsValue(1);
1702           }
1703         }
1704       }
1705       if(RI.IsNull()) continue;
1706       // read DGT entities:
1707       subs3 = graph.Sharings(SA);
1708       for(subs3.Start(); subs3.More(); subs3.Next()) {
1709         if(subs3.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
1710           // read dimensions
1711           Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
1712           if(EC.IsNull()) continue;
1713           Handle(TCollection_HAsciiString) aName;
1714           Handle(StepShape_DimensionalSize) DimSize = 
1715             Handle(StepShape_DimensionalSize)::DownCast(subs3.Value());
1716           Standard_Real dim1=-1.,dim2=-1.;
1717           subs4 = graph.Sharings(DimSize);
1718           for(subs4.Start(); subs4.More(); subs4.Next()) {
1719             Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR = 
1720               Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
1721             if(!DimCharR.IsNull()) {
1722               Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
1723               if(!SDimR.IsNull() && SDimR->NbItems()>0) {
1724                 Handle(StepRepr_RepresentationItem) RI = SDimR->ItemsValue(1);
1725                 Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(RI);
1726                 if(!VR.IsNull()) {
1727                   aName = VR->Name();
1728                   //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
1729                   //if(CID.IsNull()) continue;
1730                   //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
1731                   //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
1732                   //if(CIDM.IsNull()) continue;
1733                   //if(CIDM->ArrTransient().IsNull()) continue;
1734                   //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
1735                   //if(CID.CaseMem(CIDM)==1)
1736                   //  HARI = CID.ListRepresentationItem();
1737                   //if(CID.CaseMem(CIDM)==2)
1738                   //  HARI = CID.SetRepresentationItem();
1739                   Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
1740                   if(HARI.IsNull()) continue;
1741                   if(HARI->Length()>0) {
1742                     Handle(StepRepr_RepresentationItem) RI1 =
1743                       Handle(StepRepr_RepresentationItem)::DownCast(HARI->Value(1));
1744                     if(RI1.IsNull()) continue;
1745                     if(RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
1746                       Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
1747                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
1748                       dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
1749                       StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
1750                       Standard_Real afact=1.;
1751                       if(anUnit.IsNull()) continue;
1752                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
1753                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
1754                       if(GetLengthConversionFactor(NU,afact)) dim1=dim1*afact;
1755                     }
1756                   }
1757                   if(HARI->Length()>1) {
1758                     Handle(StepRepr_RepresentationItem) RI2 =
1759                       Handle(StepRepr_RepresentationItem)::DownCast(HARI->Value(2));
1760                     if(RI2.IsNull()) continue;
1761                     if(RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
1762                       Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
1763                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
1764                       dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
1765                       StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
1766                       Standard_Real afact=1.;
1767                       if(anUnit.IsNull()) continue;
1768                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
1769                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
1770                       if(GetLengthConversionFactor(NU,afact)) dim2 = dim2*afact;
1771                     }
1772                   }
1773                 }
1774               }
1775             }
1776           }
1777           if(dim1<0) continue;
1778           if(dim2<0) dim2=dim1;
1779           //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
1780           // now we know edge_curve and value range therefore
1781           // we can create corresponding D&GT labels
1782           Standard_Integer index = TP->MapIndex(EC);
1783           TopoDS_Shape aSh;
1784           if(index >0) {
1785             Handle(Transfer_Binder) binder = TP->MapItem(index);
1786             aSh = TransferBRep::ShapeResult(binder);
1787           }
1788           if(aSh.IsNull()) continue; 
1789           TDF_Label shL;
1790           if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
1791           Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,2);
1792           arr->SetValue(1,dim1);
1793           arr->SetValue(2,dim2);
1794           DGTTool->SetDimTol(shL,1,arr,aName,DimSize->Name());
1795         }
1796         // read tolerances and datums
1797         else if(subs3.Value()->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
1798           Handle(StepDimTol_GeometricTolerance) GT =
1799             Handle(StepDimTol_GeometricTolerance)::DownCast(subs3.Value());
1800           // read common data for tolerance
1801           //Standard_Real dim = GT->Magnitude()->ValueComponent();
1802           Handle (StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
1803           if(dim3.IsNull()) continue;
1804           Standard_Real dim = dim3->ValueComponent();
1805           StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
1806           Standard_Real afact=1.;
1807           if(anUnit.IsNull()) continue;
1808           if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
1809           Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
1810           if(GetLengthConversionFactor(NU,afact)) dim = dim*afact;
1811           //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
1812           Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,1);
1813           arr->SetValue(1,dim);
1814           Handle(TCollection_HAsciiString) aName = GT->Name();
1815           Handle(TCollection_HAsciiString) aDescription = GT->Description();
1816           Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
1817           if(AF.IsNull()) continue;
1818           Standard_Integer index = TP->MapIndex(AF);
1819           TopoDS_Shape aSh;
1820           if(index >0) {
1821             Handle(Transfer_Binder) binder = TP->MapItem(index);
1822             aSh = TransferBRep::ShapeResult(binder);
1823           }
1824           if(aSh.IsNull()) continue; 
1825           TDF_Label shL;
1826           if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
1827           // read specific data for tolerance
1828           if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
1829             Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
1830               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(subs3.Value());
1831             Standard_Integer kind=20;
1832             Handle(StepDimTol_ModifiedGeometricTolerance) MGT = 
1833               GTComplex->GetModifiedGeometricTolerance();
1834             if(!MGT.IsNull()) {
1835               kind = kind + MGT->Modifier()+1;
1836             }
1837             TDF_Label TolerL = DGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
1838             // translate datums connected with this tolerance
1839             Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
1840               GTComplex->GetGeometricToleranceWithDatumReference();
1841             if(!GTWDR.IsNull()) {
1842               ReadDatums(STool,DGTTool,graph,TP,TolerL,GTWDR);
1843             }
1844           }
1845           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
1846             Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
1847               Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(subs3.Value());
1848             if(GTWDR.IsNull()) continue;
1849             Standard_Integer kind = 0;
1850             if     (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
1851             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
1852             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
1853             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
1854             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
1855             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
1856             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
1857             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
1858             //cout<<"GTWDR: kind="<<kind<<endl;
1859             TDF_Label TolerL = DGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
1860             ReadDatums(STool,DGTTool,graph,TP,TolerL,GTWDR);
1861           }
1862           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
1863             Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
1864               Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(subs3.Value());
1865             Standard_Integer kind = 35 + MGT->Modifier();
1866             DGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
1867           }
1868           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
1869             DGTTool->SetDimTol(shL,38,arr,aName,aDescription);
1870           }
1871           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
1872             DGTTool->SetDimTol(shL,39,arr,aName,aDescription);
1873           }
1874           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
1875             DGTTool->SetDimTol(shL,40,arr,aName,aDescription);
1876           }
1877           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
1878             DGTTool->SetDimTol(shL,41,arr,aName,aDescription);
1879           }
1880           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
1881             DGTTool->SetDimTol(shL,42,arr,aName,aDescription);
1882           }
1883           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
1884             DGTTool->SetDimTol(shL,43,arr,aName,aDescription);
1885           }
1886           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
1887             DGTTool->SetDimTol(shL,44,arr,aName,aDescription);
1888           }
1889         }
1890       }
1891     }
1892   }
1893
1894   return Standard_True;
1895 }
1896
1897
1898 //=======================================================================
1899 //function : FindSolidForPDS
1900 //purpose  : auxilary
1901 //=======================================================================
1902
1903 static Handle(StepShape_SolidModel) FindSolidForPDS(const Handle(StepRepr_ProductDefinitionShape) &PDS,
1904                                                     const Interface_Graph &graph)
1905 {
1906   Handle(StepShape_SolidModel) SM;
1907   Interface_EntityIterator subs = graph.Sharings(PDS);
1908   Handle(StepShape_ShapeRepresentation) SR;
1909   for(subs.Start(); subs.More() && SM.IsNull(); subs.Next()) {
1910     Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1911       Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1912     if(SDR.IsNull()) continue;
1913     SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1914     if(SR.IsNull()) continue;
1915     for(Standard_Integer i=1; i<=SR->NbItems() && SM.IsNull(); i++) {
1916       SM = Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(i));
1917     }
1918     if(SM.IsNull()) {
1919       Interface_EntityIterator subs1 = graph.Sharings(SR);
1920       for(subs1.Start(); subs1.More() && SM.IsNull(); subs1.Next()) {
1921         Handle(StepRepr_RepresentationRelationship) RR =
1922           Handle(StepRepr_RepresentationRelationship)::DownCast(subs1.Value());
1923         if(RR.IsNull()) continue;
1924         Handle(StepShape_ShapeRepresentation) SR2;
1925         if(RR->Rep1()==SR) SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep2());
1926         else SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep1());
1927         if(SR2.IsNull()) continue;
1928         for(Standard_Integer i2=1; i2<=SR2->NbItems() && SM.IsNull(); i2++) {
1929           SM = Handle(StepShape_SolidModel)::DownCast(SR2->ItemsValue(i2));
1930         }
1931       }
1932     }
1933   }
1934   return SM;
1935 }
1936
1937
1938 //=======================================================================
1939 //function : ReadMaterials
1940 //purpose  : 
1941 //=======================================================================
1942
1943 Standard_Boolean STEPCAFControl_Reader::ReadMaterials(const Handle(XSControl_WorkSession) &WS,
1944                                                       Handle(TDocStd_Document)& Doc,
1945                                                       const Handle(TColStd_HSequenceOfTransient) &SeqPDS) const
1946 {
1947   Handle(Interface_InterfaceModel) Model = WS->Model();
1948   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1949   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1950   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1951   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( Doc->Main() );
1952   if(MatTool.IsNull()) return Standard_False;
1953   
1954   const Interface_Graph& graph = TP->Graph();
1955   for(Standard_Integer i=1; i<=SeqPDS->Length(); i++) {
1956     Handle(StepRepr_ProductDefinitionShape) PDS =
1957       Handle(StepRepr_ProductDefinitionShape)::DownCast(SeqPDS->Value(i));
1958     if(PDS.IsNull()) 
1959       continue;
1960     Handle(StepBasic_ProductDefinition) aProdDef = PDS->Definition().ProductDefinition();
1961     if(aProdDef.IsNull())
1962       continue;
1963     Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString("");
1964     Handle(TCollection_HAsciiString) aDescription = new TCollection_HAsciiString("");
1965     Handle(TCollection_HAsciiString) aDensName = new TCollection_HAsciiString("");
1966     Handle(TCollection_HAsciiString) aDensValType = new TCollection_HAsciiString("");
1967     Standard_Real aDensity=0;
1968     Interface_EntityIterator subs = graph.Sharings( aProdDef);
1969     for(subs.Start(); subs.More(); subs.Next()) {
1970       Handle(StepRepr_PropertyDefinition) PropD =
1971         Handle(StepRepr_PropertyDefinition)::DownCast(subs.Value());
1972       if(PropD.IsNull()) continue;
1973       Interface_EntityIterator subs1 = graph.Sharings(PropD);
1974       for(subs1.Start(); subs1.More(); subs1.Next()) {
1975         Handle(StepRepr_PropertyDefinitionRepresentation) PDR =
1976           Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast(subs1.Value());
1977         if(PDR.IsNull()) continue;
1978         Handle(StepRepr_Representation) Repr = PDR->UsedRepresentation();
1979         if(Repr.IsNull()) continue;
1980         Standard_Integer ir;
1981         for(ir=1; ir<=Repr->NbItems(); ir++) {
1982           Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(ir);
1983           if(RI.IsNull()) continue;
1984           if(RI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
1985             // find name and description for material
1986             Handle(StepRepr_DescriptiveRepresentationItem) DRI =
1987               Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(RI);
1988             aName = DRI->Name();
1989             
1990             aDescription = DRI->Description();
1991             if(aName.IsNull())
1992               aName = aDescription;
1993           }
1994           if(RI->IsKind(STANDARD_TYPE(StepRepr_MeasureRepresentationItem))) {
1995             // try to find density for material
1996             Handle(StepRepr_MeasureRepresentationItem) MRI =
1997               Handle(StepRepr_MeasureRepresentationItem)::DownCast(RI);
1998             aDensity = MRI->Measure()->ValueComponent();
1999             aDensName = MRI->Name();
2000             aDensValType = new TCollection_HAsciiString(MRI->Measure()->ValueComponentMember()->Name());
2001             StepBasic_Unit aUnit = MRI->Measure()->UnitComponent();
2002             if(!aUnit.IsNull()) {
2003               Handle(StepBasic_DerivedUnit) DU = aUnit.DerivedUnit();
2004               if(DU.IsNull()) continue;
2005               for(Standard_Integer idu=1; idu<=DU->NbElements(); idu++) {
2006                 Handle(StepBasic_DerivedUnitElement) DUE = DU->ElementsValue(idu);
2007                 Handle(StepBasic_NamedUnit) NU = DUE->Unit();
2008                 Standard_Real afact=1.;
2009                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit))) {
2010                   if(GetLengthConversionFactor(NU,afact)) aDensity = aDensity/(afact*afact*afact);
2011                   // transfer length value for Density from millimeter to santimeter
2012                   // in order to result density has dimension gram/(sm*sm*sm)
2013                   aDensity = aDensity*1000.;
2014                 }
2015                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit))) {
2016                   if(GetMassConversionFactor(NU,afact)) aDensity=aDensity*afact;
2017                 }
2018               }
2019             }
2020           }
2021         }
2022       }
2023     }
2024    
2025     if( aName.IsNull() || aName->Length()==0 ) 
2026       continue;
2027     // find shape label amd create Material link
2028     TopoDS_Shape aSh;
2029     Handle(StepShape_SolidModel) SM = FindSolidForPDS(PDS,graph);
2030     if(!SM.IsNull()) {
2031       Standard_Integer index = TP->MapIndex(SM);
2032       if(index >0) {
2033         Handle(Transfer_Binder) binder = TP->MapItem(index);
2034         if(!binder.IsNull())
2035           aSh = TransferBRep::ShapeResult(binder);
2036       }
2037     }
2038     if(aSh.IsNull()) continue; 
2039     TDF_Label shL;
2040     if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2041     MatTool->SetMaterial(shL,aName,aDescription,aDensity,aDensName,aDensValType);
2042   }
2043
2044   return Standard_True;
2045 }
2046
2047 //=======================================================================
2048 //function : SettleShapeData
2049 //purpose  :
2050 //=======================================================================
2051
2052 TDF_Label STEPCAFControl_Reader::SettleShapeData(const Handle(StepRepr_RepresentationItem)& theItem,
2053                                                  TDF_Label& theLab,
2054                                                  const Handle(XCAFDoc_ShapeTool)& theShapeTool,
2055                                                  const Handle(Transfer_TransientProcess)& TP) const
2056 {
2057   TDF_Label aResult = theLab;
2058
2059   Handle(TCollection_HAsciiString) hName = theItem->Name();
2060   if ( hName.IsNull() || hName->IsEmpty() )
2061     return aResult;
2062
2063   Handle(Transfer_Binder) aBinder = TP->Find(theItem);
2064   if ( aBinder.IsNull() )
2065     return aResult;
2066
2067   TopoDS_Shape aShape = TransferBRep::ShapeResult(aBinder);
2068   if ( aShape.IsNull() )
2069     return aResult;
2070
2071   // Allocate sub-Label
2072   aResult = AllocateSubLabel(theLab);
2073
2074   TCollection_AsciiString aName = hName->String();
2075   TDataStd_Name::Set(aResult, aName);
2076   theShapeTool->SetShape(aResult, aShape);
2077
2078   return aResult;
2079 }
2080
2081 //=======================================================================
2082 //function : ExpandSubShapes
2083 //purpose  :
2084 //=======================================================================
2085
2086 void STEPCAFControl_Reader::ExpandSubShapes(const Handle(XCAFDoc_ShapeTool)& ShapeTool,
2087                                             const XCAFDoc_DataMapOfShapeLabel& ShapeLabelMap,
2088                                             const STEPCAFControl_DataMapOfShapePD& ShapePDMap) const
2089 {
2090   const Handle(Transfer_TransientProcess)& TP = Reader().WS()->TransferReader()->TransientProcess();
2091   NCollection_DataMap<TopoDS_Shape, Handle(TCollection_HAsciiString)> ShapeNameMap;
2092   TColStd_MapOfTransient aRepItems;
2093
2094   // Read translation control variables
2095   Standard_Boolean doReadSNames = (Interface_Static::IVal("read.stepcaf.subshapes.name") > 0);
2096
2097   if ( !doReadSNames )
2098     return;
2099
2100   const Interface_Graph& Graph = Reader().WS()->Graph();
2101
2102   for ( STEPCAFControl_DataMapIteratorOfDataMapOfShapePD it(ShapePDMap); it.More(); it.Next() )
2103   {
2104     const TopoDS_Shape& aRootShape = it.Key();
2105     const Handle(StepBasic_ProductDefinition)& aPDef = it.Value();
2106     if ( aPDef.IsNull() )
2107       continue;
2108
2109     // Find SDR by Product
2110     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
2111     Interface_EntityIterator entIt = Graph.TypedSharings( aPDef, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation) );
2112     for ( entIt.Start(); entIt.More(); entIt.Next() )
2113     {
2114       const Handle(Standard_Transient)& aReferer = entIt.Value();
2115       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(aReferer);
2116       if ( !aSDR.IsNull() )
2117         break;
2118     }
2119
2120     if ( aSDR.IsNull() )
2121       continue;
2122
2123     // Access shape representation
2124     Handle(StepShape_ShapeRepresentation)
2125       aShapeRepr = Handle(StepShape_ShapeRepresentation)::DownCast( aSDR->UsedRepresentation() );
2126
2127     if ( aShapeRepr.IsNull() )
2128       continue;
2129
2130     // Access representation items
2131     Handle(StepRepr_HArray1OfRepresentationItem) aReprItems = aShapeRepr->Items();
2132
2133     if ( aReprItems.IsNull() )
2134       continue;
2135
2136     if ( !ShapeLabelMap.IsBound(aRootShape) )
2137       continue;
2138
2139     TDF_Label aRootLab = ShapeLabelMap.Find(aRootShape);
2140
2141     StepRepr_SequenceOfRepresentationItem aMSBSeq;
2142     StepRepr_SequenceOfRepresentationItem aSBSMSeq;
2143
2144     // Iterate over the top level representation items collecting the
2145     // topological containers to expand
2146     for ( Standard_Integer i = aReprItems->Lower(); i <= aReprItems->Upper(); ++i )
2147     {
2148       Handle(StepRepr_RepresentationItem) aTRepr = aReprItems->Value(i);
2149       if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ManifoldSolidBrep) ) )
2150         aMSBSeq.Append(aTRepr);
2151       else if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ShellBasedSurfaceModel) ) )
2152         aSBSMSeq.Append(aTRepr);
2153     }
2154
2155     // Insert intermediate OCAF Labels for SOLIDs in case there are more
2156     // than one Manifold Solid BRep in the Shape Representation
2157     Standard_Boolean doInsertSolidLab = (aMSBSeq.Length() > 1);
2158
2159     // Expand Manifold Solid BReps
2160     for ( Standard_Integer i = 1; i <= aMSBSeq.Length(); ++i )
2161     {
2162       const Handle(StepRepr_RepresentationItem)& aManiRepr = aMSBSeq.Value(i);
2163
2164       // Put additional Label for SOLID
2165       TDF_Label aManiLab;
2166       if ( doInsertSolidLab )
2167         aManiLab = SettleShapeData(aManiRepr, aRootLab, ShapeTool, TP);
2168       else
2169         aManiLab = aRootLab;
2170
2171       ExpandManifoldSolidBrep(aManiLab, aMSBSeq.Value(i), TP, ShapeTool);
2172     }
2173
2174     // Expand Shell-Based Surface Models
2175     for ( Standard_Integer i = 1; i <= aSBSMSeq.Length(); ++i )
2176       ExpandSBSM(aRootLab, aSBSMSeq.Value(i), TP, ShapeTool);
2177   }
2178 }
2179
2180 //=======================================================================
2181 //function : ExpandManifoldSolidBrep
2182 //purpose  :
2183 //=======================================================================
2184
2185 void STEPCAFControl_Reader::ExpandManifoldSolidBrep(TDF_Label& ShapeLab,
2186                                                     const Handle(StepRepr_RepresentationItem)& Repr,
2187                                                     const Handle(Transfer_TransientProcess)& TP,
2188                                                     const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
2189 {
2190   // Access outer shell
2191   Handle(StepShape_ManifoldSolidBrep) aMSB = Handle(StepShape_ManifoldSolidBrep)::DownCast(Repr);
2192   Handle(StepShape_ConnectedFaceSet) aShell = aMSB->Outer();
2193
2194   // Expand shell contents to CAF tree
2195   ExpandShell(aShell, ShapeLab, TP, ShapeTool);
2196 }
2197
2198 //=======================================================================
2199 //function : ExpandSBSM
2200 //purpose  :
2201 //=======================================================================
2202
2203 void STEPCAFControl_Reader::ExpandSBSM(TDF_Label& ShapeLab,
2204                                        const Handle(StepRepr_RepresentationItem)& Repr,
2205                                        const Handle(Transfer_TransientProcess)& TP,
2206                                        const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
2207 {
2208   Handle(StepShape_ShellBasedSurfaceModel) aSBSM = Handle(StepShape_ShellBasedSurfaceModel)::DownCast(Repr);
2209
2210   // Access boundary shells
2211   Handle(StepShape_HArray1OfShell) aShells = aSBSM->SbsmBoundary();
2212   for ( Standard_Integer s = aShells->Lower(); s <= aShells->Upper(); ++s )
2213   {
2214     const StepShape_Shell& aShell = aShells->Value(s);
2215     Handle(StepShape_ConnectedFaceSet) aCFS;
2216     Handle(StepShape_OpenShell) anOpenShell = aShell.OpenShell();
2217     Handle(StepShape_ClosedShell) aClosedShell = aShell.ClosedShell();
2218
2219     if ( !anOpenShell.IsNull() )
2220       aCFS = anOpenShell;
2221     else
2222       aCFS = aClosedShell;
2223
2224     ExpandShell(aCFS, ShapeLab, TP, ShapeTool);
2225   }
2226 }
2227
2228 //=======================================================================
2229 //function : ExpandShell
2230 //purpose  :
2231 //=======================================================================
2232
2233 void STEPCAFControl_Reader::ExpandShell(const Handle(StepShape_ConnectedFaceSet)& Shell,
2234                                         TDF_Label& RootLab,
2235                                         const Handle(Transfer_TransientProcess)& TP,
2236                                         const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
2237 {
2238   // Record CAF data
2239   TDF_Label aShellLab = SettleShapeData(Shell, RootLab, ShapeTool, TP);
2240
2241   // Access faces
2242   Handle(StepShape_HArray1OfFace) aFaces = Shell->CfsFaces();
2243   for ( Standard_Integer f = aFaces->Lower(); f <= aFaces->Upper(); ++f )
2244   {
2245     const Handle(StepShape_Face)& aFace = aFaces->Value(f);
2246
2247     // Record CAF data
2248     TDF_Label aFaceLab = SettleShapeData(aFace, aShellLab, ShapeTool, TP);
2249
2250     // Access face bounds
2251     Handle(StepShape_HArray1OfFaceBound) aWires = aFace->Bounds();
2252     for ( Standard_Integer w = aWires->Lower(); w <= aWires->Upper(); ++w )
2253     {
2254       const Handle(StepShape_Loop)& aWire = aWires->Value(w)->Bound();
2255
2256       // Record CAF data
2257       TDF_Label aWireLab = SettleShapeData(aWire, aFaceLab, ShapeTool, TP);
2258
2259       // Access wire edges
2260       // Currently only EDGE LOOPs are considered (!)
2261       if ( !aWire->IsInstance( STANDARD_TYPE(StepShape_EdgeLoop) ) )
2262         continue;
2263
2264       // Access edges
2265       Handle(StepShape_EdgeLoop) anEdgeLoop = Handle(StepShape_EdgeLoop)::DownCast(aWire);
2266       Handle(StepShape_HArray1OfOrientedEdge) anEdges = anEdgeLoop->EdgeList();
2267       for ( Standard_Integer e = anEdges->Lower(); e <= anEdges->Upper(); ++e )
2268       {
2269         Handle(StepShape_Edge) anEdge = anEdges->Value(e)->EdgeElement();
2270
2271         // Record CAF data
2272         TDF_Label anEdgeLab = SettleShapeData(anEdge, aWireLab, ShapeTool, TP);
2273
2274         // Access vertices
2275         Handle(StepShape_Vertex) aV1 = anEdge->EdgeStart();
2276         Handle(StepShape_Vertex) aV2 = anEdge->EdgeEnd();
2277
2278         // Record CAF data
2279         SettleShapeData(aV1, anEdgeLab, ShapeTool, TP);
2280         SettleShapeData(aV2, anEdgeLab, ShapeTool, TP);
2281       }
2282     }
2283   }
2284 }
2285
2286 //=======================================================================
2287 //function : SetColorMode
2288 //purpose  : 
2289 //=======================================================================
2290
2291 void STEPCAFControl_Reader::SetColorMode (const Standard_Boolean colormode)
2292 {
2293   myColorMode = colormode;
2294 }
2295
2296 //=======================================================================
2297 //function : GetColorMode
2298 //purpose  : 
2299 //=======================================================================
2300
2301 Standard_Boolean STEPCAFControl_Reader::GetColorMode () const
2302 {
2303   return myColorMode;
2304 }
2305
2306 //=======================================================================
2307 //function : SetNameMode
2308 //purpose  : 
2309 //=======================================================================
2310
2311 void STEPCAFControl_Reader::SetNameMode (const Standard_Boolean namemode)
2312 {
2313   myNameMode = namemode;
2314 }
2315
2316 //=======================================================================
2317 //function : GetNameMode
2318 //purpose  : 
2319 //=======================================================================
2320
2321 Standard_Boolean STEPCAFControl_Reader::GetNameMode () const
2322 {
2323   return myNameMode;
2324 }
2325
2326 //=======================================================================
2327 //function : SetLayerMode
2328 //purpose  : 
2329 //=======================================================================
2330
2331 void STEPCAFControl_Reader::SetLayerMode (const Standard_Boolean layermode)
2332 {
2333   myLayerMode = layermode;
2334 }
2335
2336 //=======================================================================
2337 //function : GetLayerMode
2338 //purpose  : 
2339 //=======================================================================
2340
2341 Standard_Boolean STEPCAFControl_Reader::GetLayerMode () const
2342 {
2343   return myLayerMode;
2344 }
2345
2346 //=======================================================================
2347 //function : SetPropsMode
2348 //purpose  : 
2349 //=======================================================================
2350
2351 void STEPCAFControl_Reader::SetPropsMode (const Standard_Boolean propsmode)
2352 {
2353   myPropsMode = propsmode;
2354 }
2355
2356 //=======================================================================
2357 //function : GetPropsMode
2358 //purpose  : 
2359 //=======================================================================
2360
2361 Standard_Boolean STEPCAFControl_Reader::GetPropsMode () const
2362 {
2363   return myPropsMode;
2364 }
2365
2366 //=======================================================================
2367 //function : SetSHUOMode
2368 //purpose  : 
2369 //=======================================================================
2370
2371 void STEPCAFControl_Reader::SetSHUOMode (const Standard_Boolean mode)
2372 {
2373   mySHUOMode = mode;
2374 }
2375
2376 //=======================================================================
2377 //function : GetSHUOMode
2378 //purpose  : 
2379 //=======================================================================
2380
2381 Standard_Boolean STEPCAFControl_Reader::GetSHUOMode () const
2382 {
2383   return mySHUOMode;
2384 }
2385
2386 //=======================================================================
2387 //function : SetGDTMode
2388 //purpose  : 
2389 //=======================================================================
2390
2391 void STEPCAFControl_Reader::SetGDTMode (const Standard_Boolean gdtmode)
2392 {
2393   myGDTMode = gdtmode;
2394 }
2395
2396 //=======================================================================
2397 //function : GetGDTMode
2398 //purpose  : 
2399 //=======================================================================
2400
2401 Standard_Boolean STEPCAFControl_Reader::GetGDTMode () const
2402 {
2403   return myGDTMode;
2404 }
2405
2406
2407 //=======================================================================
2408 //function : SetMatMode
2409 //purpose  : 
2410 //=======================================================================
2411
2412 void STEPCAFControl_Reader::SetMatMode (const Standard_Boolean matmode)
2413 {
2414   myMatMode = matmode;
2415 }
2416
2417 //=======================================================================
2418 //function : GetMatMode
2419 //purpose  : 
2420 //=======================================================================
2421
2422 Standard_Boolean STEPCAFControl_Reader::GetMatMode () const
2423 {
2424   return myMatMode;
2425 }