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