21eb2d22c808e2700c8e3aae403b6012fadbf197
[occt.git] / src / STEPCAFControl / STEPCAFControl_Reader.cxx
1 // Created on: 2000-08-15
2 // Created by: Andrey BETENEV
3 // Copyright (c) 2000-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16
17 #include <BRep_Builder.hxx>
18 #include <Interface_EntityIterator.hxx>
19 #include <Interface_InterfaceModel.hxx>
20 #include <StepData_StepModel.hxx>
21 #include <HeaderSection_FileSchema.hxx>
22 #include <Interface_Static.hxx>
23 #include <NCollection_DataMap.hxx>
24 #include <OSD_Path.hxx>
25 #include <Quantity_Color.hxx>
26 #include <StepAP214_AppliedExternalIdentificationAssignment.hxx>
27 #include <StepBasic_ConversionBasedUnitAndLengthUnit.hxx>
28 #include <StepBasic_ConversionBasedUnitAndPlaneAngleUnit.hxx>
29 #include <StepBasic_ConversionBasedUnitAndMassUnit.hxx>
30 #include <StepBasic_DerivedUnit.hxx>
31 #include <StepBasic_DerivedUnitElement.hxx>
32 #include <StepBasic_MeasureValueMember.hxx>
33 #include <StepBasic_MeasureWithUnit.hxx>
34 #include <StepBasic_NamedUnit.hxx>
35 #include <StepBasic_Product.hxx>
36 #include <StepBasic_ProductDefinition.hxx>
37 #include <StepBasic_ProductDefinitionFormation.hxx>
38 #include <StepBasic_ProductDefinitionRelationship.hxx>
39 #include <StepBasic_SiUnit.hxx>
40 #include <StepBasic_Unit.hxx>
41 #include <STEPCAFControl_Controller.hxx>
42 #include <STEPCAFControl_DataMapIteratorOfDataMapOfShapePD.hxx>
43 #include <STEPCAFControl_DataMapOfPDExternFile.hxx>
44 #include <STEPCAFControl_DataMapOfSDRExternFile.hxx>
45 #include <STEPCAFControl_DataMapOfShapePD.hxx>
46 #include <STEPCAFControl_DictionaryOfExternFile.hxx>
47 #include <STEPCAFControl_ExternFile.hxx>
48 #include <STEPCAFControl_Reader.hxx>
49 #include <STEPConstruct.hxx>
50 #include <STEPConstruct_Assembly.hxx>
51 #include <STEPConstruct_ExternRefs.hxx>
52 #include <STEPConstruct_Styles.hxx>
53 #include <STEPConstruct_Tool.hxx>
54 #include <STEPConstruct_UnitContext.hxx>
55 #include <STEPConstruct_ValidationProps.hxx>
56 #include <STEPControl_Reader.hxx>
57 #include <StepGeom_GeometricRepresentationItem.hxx>
58 #include <StepGeom_Axis2Placement3d.hxx>
59 #include <StepGeom_Direction.hxx>
60 #include <StepDimTol_AngularityTolerance.hxx>
61 #include <StepDimTol_CircularRunoutTolerance.hxx>
62 #include <StepDimTol_CoaxialityTolerance.hxx>
63 #include <StepDimTol_ConcentricityTolerance.hxx>
64 #include <StepDimTol_CylindricityTolerance.hxx>
65 #include <StepDimTol_Datum.hxx>
66 #include <StepDimTol_DatumFeature.hxx>
67 #include <StepDimTol_DatumReference.hxx>
68 #include <StepDimTol_DatumReferenceElement.hxx>
69 #include <StepDimTol_DatumReferenceCompartment.hxx>
70 #include <StepDimTol_DatumSystem.hxx>
71 #include <StepDimTol_FlatnessTolerance.hxx>
72 #include <StepDimTol_GeometricTolerance.hxx>
73 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
74 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
75 #include <StepDimTol_GeoTolAndGeoTolWthDatRef.hxx>
76 #include <StepDimTol_HArray1OfDatumReference.hxx>
77 #include <StepDimTol_LineProfileTolerance.hxx>
78 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
79 #include <StepDimTol_ParallelismTolerance.hxx>
80 #include <StepDimTol_PerpendicularityTolerance.hxx>
81 #include <StepDimTol_PositionTolerance.hxx>
82 #include <StepDimTol_ProjectedZoneDefinition.hxx>
83 #include <StepDimTol_RoundnessTolerance.hxx>
84 #include <StepDimTol_RunoutZoneDefinition.hxx>
85 #include <StepDimTol_StraightnessTolerance.hxx>
86 #include <StepDimTol_SurfaceProfileTolerance.hxx>
87 #include <StepDimTol_SymmetryTolerance.hxx>
88 #include <StepDimTol_ToleranceZone.hxx>
89 #include <StepDimTol_ToleranceZoneForm.hxx>
90 #include <StepDimTol_TotalRunoutTolerance.hxx>
91 #include <StepDimTol_GeometricToleranceWithModifiers.hxx>
92 #include <StepDimTol_HArray1OfGeometricToleranceModifier.hxx>
93 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod.hxx>
94 #include <StepDimTol_GeoTolAndGeoTolWthMod.hxx>
95 #include <StepDimTol_GeometricToleranceWithMaximumTolerance.hxx>
96 #include <StepDimTol_PlacedDatumTargetFeature.hxx>
97 #include <StepRepr_AssemblyComponentUsage.hxx>
98 #include <StepRepr_CharacterizedDefinition.hxx>
99 #include <StepRepr_CompoundRepresentationItem.hxx>
100 #include <StepRepr_DescriptiveRepresentationItem.hxx>
101 #include <StepRepr_HArray1OfRepresentationItem.hxx>
102 #include <StepRepr_MeasureRepresentationItem.hxx>
103 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
104 #include <StepRepr_ProductDefinitionShape.hxx>
105 #include <StepRepr_PropertyDefinition.hxx>
106 #include <StepRepr_PropertyDefinitionRepresentation.hxx>
107 #include <StepRepr_Representation.hxx>
108 #include <StepRepr_RepresentationItem.hxx>
109 #include <StepRepr_HArray1OfRepresentationItem.hxx>
110 #include <StepRepr_RepresentationRelationship.hxx>
111 #include <StepRepr_RepresentedDefinition.hxx>
112 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
113 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnit.hxx>
114 #include <StepRepr_SequenceOfRepresentationItem.hxx>
115 #include <StepRepr_ShapeAspect.hxx>
116 #include <StepRepr_CompositeShapeAspect.hxx>
117 #include <StepRepr_AllAroundShapeAspect.hxx>
118 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
119 #include <StepRepr_ShapeAspectRelationship.hxx>
120 #include <StepRepr_ShapeRepresentationRelationship.hxx>
121 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
122 #include <StepRepr_ValueRange.hxx>
123 #include <StepRepr_FeatureForDatumTargetRelationship.hxx>
124 #include <StepShape_AdvancedFace.hxx>
125 #include <StepShape_AdvancedBrepShapeRepresentation.hxx>
126 #include <StepShape_AngleRelator.hxx>
127 #include <StepShape_AngularSize.hxx>
128 #include <StepShape_AngularLocation.hxx>
129 #include <StepShape_ClosedShell.hxx>
130 #include <StepShape_ConnectedFaceSet.hxx>
131 #include <StepShape_ContextDependentShapeRepresentation.hxx>
132 #include <StepRepr_CompGroupShAspAndCompShAspAndDatumFeatAndShAsp.hxx>
133 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
134 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
135 #include <StepShape_DimensionalSizeWithPath.hxx>
136 #include <StepShape_DimensionalLocationWithPath.hxx>
137 #include <StepShape_ShapeDimensionRepresentationItem.hxx>
138 #include <StepShape_ShapeRepresentationWithParameters.hxx>
139 #include <StepShape_HArray1OfShapeDimensionRepresentationItem.hxx>
140 #include <StepShape_DimensionalSize.hxx>
141 #include <StepShape_DimensionalLocation.hxx>
142 #include <StepShape_EdgeCurve.hxx>
143 #include <StepShape_EdgeLoop.hxx>
144 #include <StepShape_GeometricSet.hxx>
145 #include <StepShape_HArray1OfFace.hxx>
146 #include <StepShape_HArray1OfFaceBound.hxx>
147 #include <StepShape_HArray1OfOrientedEdge.hxx>
148 #include <StepShape_HArray1OfShell.hxx>
149 #include <StepShape_LimitsAndFits.hxx>
150 #include <StepShape_Loop.hxx>
151 #include <StepShape_ManifoldSolidBrep.hxx>
152 #include <StepShape_PlusMinusTolerance.hxx>
153 #include <StepShape_QualifiedRepresentationItem.hxx>
154 #include <StepShape_OpenShell.hxx>
155 #include <StepShape_ShapeDefinitionRepresentation.hxx>
156 #include <StepShape_ShapeDimensionRepresentation.hxx>
157 #include <StepShape_ShapeRepresentation.hxx>
158 #include <StepShape_ShellBasedSurfaceModel.hxx>
159 #include <StepShape_SolidModel.hxx>
160 #include <StepShape_ToleranceMethodDefinition.hxx>
161 #include <StepShape_ToleranceValue.hxx>
162 #include <StepShape_ValueFormatTypeQualifier.hxx>
163 #include <StepShape_Vertex.hxx>
164 #include <StepVisual_Invisibility.hxx>
165 #include <StepVisual_LayeredItem.hxx>
166 #include <StepVisual_PresentationLayerAssignment.hxx>
167 #include <StepVisual_PresentationStyleByContext.hxx>
168 #include <StepVisual_StyleContextSelect.hxx>
169 #include <StepVisual_StyledItem.hxx>
170 #include <StepShape_TypeQualifier.hxx>
171 #include <TCollection_AsciiString.hxx>
172 #include <TCollection_HAsciiString.hxx>
173 #include <TColStd_HArray1OfReal.hxx>
174 #include <TColStd_HArray1OfTransient.hxx>
175 #include <TColStd_HSequenceOfTransient.hxx>
176 #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
177 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
178 #include <TColStd_MapOfTransient.hxx>
179 #include <TColStd_SequenceOfHAsciiString.hxx>
180 #include <TDataStd_Name.hxx>
181 #include <TDataStd_TreeNode.hxx>
182 #include <TDataStd_UAttribute.hxx>
183 #include <TDF_Label.hxx>
184 #include <TDF_Tool.hxx>
185 #include <TDocStd_Document.hxx>
186 #include <TNaming_NamedShape.hxx>
187 #include <TopoDS.hxx>
188 #include <TopoDS_Compound.hxx>
189 #include <TopoDS_Iterator.hxx>
190 #include <TopoDS_Shape.hxx>
191 #include <TopTools_ListIteratorOfListOfShape.hxx>
192 #include <TopTools_ListOfShape.hxx>
193 #include <TopTools_MapOfShape.hxx>
194 #include <Transfer_Binder.hxx>
195 #include <Transfer_TransientProcess.hxx>
196 #include <TransferBRep.hxx>
197 #include <XCAFDoc.hxx>
198 #include <XCAFDoc_Area.hxx>
199 #include <XCAFDoc_Centroid.hxx>
200 #include <XCAFDoc_ColorTool.hxx>
201 #include <XCAFDoc_DataMapOfShapeLabel.hxx>
202 #include <XCAFDoc_DimTolTool.hxx>
203 #include <XCAFDoc_Dimension.hxx>
204 #include <XCAFDoc_Datum.hxx>
205 #include <XCAFDoc_GeomTolerance.hxx>
206 #include <XCAFDoc_DocumentTool.hxx>
207 #include <XCAFDoc_GraphNode.hxx>
208 #include <XCAFDoc_LayerTool.hxx>
209 #include <XCAFDoc_MaterialTool.hxx>
210 #include <XCAFDoc_ShapeTool.hxx>
211 #include <XCAFDoc_Volume.hxx>
212 #include <XCAFDimTolObjects_DimensionModifiersSequence.hxx>
213 #include <XCAFDimTolObjects_GeomToleranceType.hxx>
214 #include <XCAFDimTolObjects_DimensionObject.hxx>
215 #include <XCAFDimTolObjects_GeomToleranceObject.hxx>
216 #include <XCAFDimTolObjects_DatumObject.hxx>
217 #include <XSControl_TransferReader.hxx>
218 #include <XSControl_WorkSession.hxx>
219 #include <StepAP242_GeometricItemSpecificUsage.hxx>
220 #include <StepGeom_CartesianPoint.hxx>
221 #include <STEPConstruct_GDTProperty.hxx>
222 // skl 21.08.2003 for reading G&DT
223 //#include <StepRepr_CompoundItemDefinition.hxx>
224 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
225 //#include <StepBasic_ConversionBasedUnit.hxx>
226 //#include <TDataStd_Real.hxx>
227 //#include <TDataStd_Constraint.hxx>
228 //#include <TDataStd_ConstraintEnum.hxx>
229 //#include <TNaming_Tool.hxx>
230 //#include <AIS_InteractiveObject.hxx>
231 //#include <TPrsStd_ConstraintTools.hxx>
232 //#include <AIS_DiameterDimension.hxx>
233 //#include <TPrsStd_Position.hxx>
234 //#include <TPrsStd_AISPresentation.hxx>
235 //#include <TNaming_Builder.hxx>
236 #ifdef OCCT_DEBUG
237 //! Converts address of the passed shape (TShape) to string.
238 //! \param theShape [in] Shape to dump.
239 //! \return corresponding string.
240 TCollection_AsciiString AddrToString(const TopoDS_Shape& theShape)
241 {
242   std::string anAddrStr;
243   std::ostringstream ost;
244   ost << theShape.TShape().get();
245   anAddrStr = ost.str();
246
247   TCollection_AsciiString aStr =
248     TCollection_AsciiString("[").Cat( anAddrStr.c_str() ).Cat("]");
249
250   return aStr;
251 }
252 #endif
253
254 //=======================================================================
255 //function : IsEqual
256 //purpose  : global function to check equality of topological shapes
257 //=======================================================================
258
259 inline Standard_Boolean IsEqual(const TopoDS_Shape& theShape1,
260                                 const TopoDS_Shape& theShape2) 
261 {
262   return theShape1.IsEqual(theShape2);
263 }
264
265 //=======================================================================
266 //function : AllocateSubLabel
267 //purpose  :
268 //=======================================================================
269
270 static TDF_Label AllocateSubLabel(TDF_Label& theRoot)
271 {
272   return TDF_TagSource::NewChild(theRoot);
273 }
274
275 //=======================================================================
276 //function : STEPCAFControl_Reader
277 //purpose  : 
278 //=======================================================================
279
280 STEPCAFControl_Reader::STEPCAFControl_Reader ():
281        myColorMode( Standard_True ),
282        myNameMode ( Standard_True ),
283        myLayerMode( Standard_True ),
284        myPropsMode( Standard_True ),
285            mySHUOMode ( Standard_False ),
286        myGDTMode  ( Standard_True ),
287        myMatMode  ( Standard_True )
288 {
289   STEPCAFControl_Controller::Init();
290   myFiles = new STEPCAFControl_DictionaryOfExternFile;
291 }
292
293
294 //=======================================================================
295 //function : STEPCAFControl_Reader
296 //purpose  : 
297 //=======================================================================
298
299 STEPCAFControl_Reader::STEPCAFControl_Reader (const Handle(XSControl_WorkSession)& WS,
300                                               const Standard_Boolean scratch) :
301        myColorMode( Standard_True ),
302        myNameMode ( Standard_True ),
303        myLayerMode( Standard_True ),
304        myPropsMode( Standard_True ),
305            mySHUOMode ( Standard_False ),
306        myGDTMode  ( Standard_True ),
307        myMatMode  ( Standard_True )
308 {
309   STEPCAFControl_Controller::Init();
310   Init ( WS, scratch );
311 }
312
313
314 //=======================================================================
315 //function : Init
316 //purpose  : 
317 //=======================================================================
318
319 void STEPCAFControl_Reader::Init (const Handle(XSControl_WorkSession)& WS,
320                                   const Standard_Boolean scratch)
321 {
322 // necessary only in Writer, to set good actor:  WS->SelectNorm ( "STEP" );
323   myReader.SetWS (WS,scratch);
324   myFiles = new STEPCAFControl_DictionaryOfExternFile;
325 }
326
327
328 //=======================================================================
329 //function : ReadFile
330 //purpose  : 
331 //=======================================================================
332
333 IFSelect_ReturnStatus STEPCAFControl_Reader::ReadFile (const Standard_CString filename)
334 {
335   return myReader.ReadFile ( filename );
336 }
337
338
339 //=======================================================================
340 //function : NbRootsForTransfer
341 //purpose  : 
342 //=======================================================================
343
344 Standard_Integer STEPCAFControl_Reader::NbRootsForTransfer () 
345 {
346   return myReader.NbRootsForTransfer();
347 }
348
349
350 //=======================================================================
351 //function : TransferOneRoot
352 //purpose  : 
353 //=======================================================================
354
355 Standard_Boolean STEPCAFControl_Reader::TransferOneRoot (const Standard_Integer num,
356                                                          Handle(TDocStd_Document) &doc) 
357 {
358   TDF_LabelSequence Lseq;
359   return Transfer ( myReader, num, doc, Lseq );
360 }
361
362
363 //=======================================================================
364 //function : Transfer
365 //purpose  : 
366 //=======================================================================
367
368 Standard_Boolean STEPCAFControl_Reader::Transfer (Handle(TDocStd_Document) &doc)
369 {
370   TDF_LabelSequence Lseq;
371   return Transfer ( myReader, 0, doc, Lseq );
372 }
373
374
375 //=======================================================================
376 //function : Perform
377 //purpose  : 
378 //=======================================================================
379
380 Standard_Boolean STEPCAFControl_Reader::Perform (const Standard_CString filename,
381                                                  Handle(TDocStd_Document) &doc)
382 {
383   if ( ReadFile ( filename ) != IFSelect_RetDone ) return Standard_False;
384   return Transfer ( doc );
385 }
386   
387
388 //=======================================================================
389 //function : Perform
390 //purpose  : 
391 //=======================================================================
392
393 Standard_Boolean STEPCAFControl_Reader::Perform (const TCollection_AsciiString &filename,
394                                                  Handle(TDocStd_Document) &doc)
395 {
396   if ( ReadFile ( filename.ToCString() ) != IFSelect_RetDone ) return Standard_False;
397   return Transfer ( doc );
398 }
399   
400
401 //=======================================================================
402 //function : ExternFiles
403 //purpose  : 
404 //=======================================================================
405
406 const Handle(STEPCAFControl_DictionaryOfExternFile) &STEPCAFControl_Reader::ExternFiles () const
407 {
408   return myFiles;
409 }
410         
411
412 //=======================================================================
413 //function : ExternFile
414 //purpose  : 
415 //=======================================================================
416
417 Standard_Boolean STEPCAFControl_Reader::ExternFile (const Standard_CString name,
418                                                     Handle(STEPCAFControl_ExternFile) &ef) const
419 {
420   ef.Nullify();
421   if ( myFiles.IsNull() || ! myFiles->HasItem ( name ) ) 
422     return Standard_False;
423   ef = myFiles->Item ( name );
424   return Standard_True;
425 }
426
427
428 //=======================================================================
429 //function : Reader
430 //purpose  : 
431 //=======================================================================
432
433 STEPControl_Reader &STEPCAFControl_Reader::ChangeReader () 
434 {
435   return myReader;
436 }
437   
438
439 //=======================================================================
440 //function : Reader
441 //purpose  : 
442 //=======================================================================
443
444 const STEPControl_Reader &STEPCAFControl_Reader::Reader () const
445 {
446   return myReader;
447 }
448   
449
450 //=======================================================================
451 //function : FillShapesMap
452 //purpose  : auxiliary: fill a map by all compounds and their components
453 //=======================================================================
454
455 static void FillShapesMap (const TopoDS_Shape &S, TopTools_MapOfShape &map)
456 {
457   TopoDS_Shape S0 = S;
458   TopLoc_Location loc;
459   S0.Location ( loc );
460   map.Add ( S0 );
461   if ( S.ShapeType() != TopAbs_COMPOUND ) return;
462   for ( TopoDS_Iterator it(S); it.More(); it.Next() ) 
463     FillShapesMap ( it.Value(), map );
464 }
465
466
467 //=======================================================================
468 //function : Transfer
469 //purpose  : basic working method
470 //=======================================================================
471
472 Standard_Boolean STEPCAFControl_Reader::Transfer (STEPControl_Reader &reader,
473                                                   const Standard_Integer nroot,
474                                                   Handle(TDocStd_Document) &doc,
475                                                   TDF_LabelSequence &Lseq,
476                                                   const Standard_Boolean asOne)
477 {
478   reader.ClearShapes();
479   Standard_Integer i;
480   
481   // Read all shapes
482   Standard_Integer num = reader.NbRootsForTransfer();
483   if ( num <=0 ) return Standard_False;
484   if ( nroot ) {
485     if ( nroot > num ) return Standard_False;
486     reader.TransferOneRoot ( nroot );
487   }
488   else {
489     for ( i=1; i <= num; i++ ) reader.TransferOneRoot ( i );
490   }
491   num = reader.NbShapes();
492   if ( num <=0 ) return Standard_False;
493
494   // Fill a map of (top-level) shapes resulting from that transfer
495   // Only these shapes will be considered further
496   TopTools_MapOfShape ShapesMap, NewShapesMap;
497   for ( i=1; i <= num; i++ ) FillShapesMap ( reader.Shape(i), ShapesMap );
498   
499   // Collect information on shapes originating from SDRs
500   // this will be used to distinguish compounds representing assemblies
501   // from the ones representing hybrid models and shape sets
502   STEPCAFControl_DataMapOfShapePD ShapePDMap;
503   STEPCAFControl_DataMapOfPDExternFile PDFileMap;
504   Handle(Interface_InterfaceModel) Model = reader.Model();
505   Handle(Transfer_TransientProcess) TP = reader.WS()->TransferReader()->TransientProcess();
506   Standard_Integer nb = Model->NbEntities();
507
508   Handle(TColStd_HSequenceOfTransient) SeqPDS = new TColStd_HSequenceOfTransient;
509
510   for (i = 1; i <= nb; i ++) {
511     Handle(Standard_Transient) enti = Model->Value(i);
512     if(enti->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) {
513       // sequence for acceleration ReadMaterials
514       SeqPDS->Append(enti);
515     }
516     if ( enti->IsKind ( STANDARD_TYPE(StepBasic_ProductDefinition ) ) ) {
517       Handle(StepBasic_ProductDefinition) PD = 
518         Handle(StepBasic_ProductDefinition)::DownCast(enti);
519       Standard_Integer index = TP->MapIndex(PD);
520       if ( index >0 ) {
521         Handle(Transfer_Binder) binder = TP->MapItem (index);
522         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
523         if ( ! S.IsNull() && ShapesMap.Contains(S) ) {
524           NewShapesMap.Add(S);
525           ShapePDMap.Bind ( S, PD ); 
526           Handle(STEPCAFControl_ExternFile) EF;
527           PDFileMap.Bind ( PD, EF );
528         }
529       }
530     }
531     if ( enti->IsKind ( STANDARD_TYPE(StepShape_ShapeRepresentation) ) ) {
532       Standard_Integer index = TP->MapIndex(enti);
533       if ( index >0 ) {
534         Handle(Transfer_Binder) binder = TP->MapItem (index);
535         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
536         if ( ! S.IsNull() && ShapesMap.Contains(S) )
537           NewShapesMap.Add(S);
538       }
539     }
540   }
541
542   // get directory name of the main file
543   OSD_Path mainfile ( reader.WS()->LoadedFile() );
544   mainfile.SetName ( "" );
545   mainfile.SetExtension ( "" );
546   TCollection_AsciiString dpath;
547   mainfile.SystemName ( dpath );
548
549   // Load external references (only for relevant SDRs)
550   // and fill map SDR -> extern file
551   STEPConstruct_ExternRefs ExtRefs ( reader.WS() );
552   ExtRefs.LoadExternRefs();
553   for ( i=1; i <= ExtRefs.NbExternRefs(); i++ ) {
554     // check extern ref format
555     Handle(TCollection_HAsciiString) format = ExtRefs.Format(i);
556     if ( ! format.IsNull() ) {
557       static Handle(TCollection_HAsciiString) ap203 = new TCollection_HAsciiString ( "STEP AP203" );
558       static Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "STEP AP214" );
559       if ( ! format->IsSameString ( ap203, Standard_False ) && 
560            ! format->IsSameString ( ap214, Standard_False ) ) {
561 #ifdef OCCT_DEBUG
562         cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document is neither STEP AP203 nor AP214" << endl;
563 #else
564         continue;
565 #endif
566       }
567     }
568 #ifdef OCCT_DEBUG
569     else cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document format not defined" << endl;
570 #endif
571     
572     // get and check filename of the current extern ref
573     const Standard_CString filename = ExtRefs.FileName(i);
574
575 #ifdef OCCT_DEBUG
576     cout<<"filename="<<filename<<endl;
577 #endif
578
579     if ( ! filename || ! filename[0] ) {
580 #ifdef OCCT_DEBUG
581       cout << "Warning: STEPCAFControl_Reader::Transfer: Extern reference file name is empty" << endl;
582 #endif
583       continue; // not a valid extern ref
584     }
585
586     // compute true path to the extern file
587     TCollection_AsciiString fullname = OSD_Path::AbsolutePath ( dpath, filename );
588     if ( fullname.Length() <= 0 ) fullname = filename;
589
590 /*    
591     char fullname[1024];
592     char *mainfile = reader.WS()->LoadedFile();
593     if ( ! mainfile ) mainfile = "";
594     Standard_Integer slash = 0;
595     for ( Standard_Integer k=0; mainfile[k]; k++ )
596       if ( mainfile[k] == '/' ) slash = k;
597     strncpy ( fullname, mainfile, slash );
598     sprintf ( &fullname[slash], "%s%s", ( mainfile[0] ? "/" : "" ), filename );
599 */
600     
601     // get and check PD associated with the current extern ref
602     Handle(StepBasic_ProductDefinition) PD = ExtRefs.ProdDef(i);
603     if ( PD.IsNull() ) continue; // not a valid extern ref
604     if ( ! PDFileMap.IsBound ( PD ) ) continue; // this PD is not concerned by current transfer
605     
606     // read extern file (or use existing data) and record its data
607     Handle(STEPCAFControl_ExternFile) EF = 
608       ReadExternFile ( filename, fullname.ToCString(), doc );
609     PDFileMap.Bind ( PD, EF );
610   }
611   
612   // and insert them to the document
613   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
614   if ( STool.IsNull() ) return Standard_False;
615   XCAFDoc_DataMapOfShapeLabel map;
616   if ( asOne )
617     Lseq.Append ( AddShape ( reader.OneShape(), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
618   else {
619     for ( i=1; i <= num; i++ ) {
620       Lseq.Append ( AddShape ( reader.Shape(i), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
621     }
622   }
623   
624   // read colors
625   if ( GetColorMode() )
626     ReadColors ( reader.WS(), doc, PDFileMap, map );
627   
628   // read names
629   if ( GetNameMode() )
630     ReadNames ( reader.WS(), doc, PDFileMap, map );
631
632   // read validation props
633   if ( GetPropsMode() )
634     ReadValProps ( reader.WS(), doc, PDFileMap, map );
635
636   // read layers
637   if ( GetLayerMode() )
638     ReadLayers ( reader.WS(), doc );
639   
640   // read SHUO entities from STEP model
641   if ( GetSHUOMode() )
642     ReadSHUOs ( reader.WS(), doc, PDFileMap, map );
643
644   // read GDT entities from STEP model
645   if(GetGDTMode())
646     ReadGDTs(reader.WS(),doc);
647
648   // read Material entities from STEP model
649   if(GetMatMode())
650     ReadMaterials(reader.WS(),doc,SeqPDS);
651
652   // Expand resulting CAF structure for sub-shapes (optionally with their
653   // names) if requested
654   ExpandSubShapes(STool, map, ShapePDMap);
655
656   return Standard_True;
657 }
658
659 //=======================================================================
660 //function : AddShape
661 //purpose  : 
662 //=======================================================================
663
664 TDF_Label STEPCAFControl_Reader::AddShape (const TopoDS_Shape &S, 
665                                            const Handle(XCAFDoc_ShapeTool) &STool,
666                                            const TopTools_MapOfShape &NewShapesMap,
667                                            const STEPCAFControl_DataMapOfShapePD &ShapePDMap,
668                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
669                                            XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
670 {
671   // if shape has already been mapped, just return corresponding label
672   if ( ShapeLabelMap.IsBound ( S ) ) {
673     return ShapeLabelMap.Find ( S );
674   }
675   
676   // if shape is located, create instance
677   if ( ! S.Location().IsIdentity() ) {
678     TopoDS_Shape S0 = S;
679     TopLoc_Location loc;
680     S0.Location ( loc );
681     AddShape ( S0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
682     TDF_Label L = STool->AddShape ( S, Standard_False ); // should create reference
683     ShapeLabelMap.Bind ( S, L );
684     return L;
685   }
686   
687   // if shape is not compound, simple add it
688   if ( S.ShapeType() != TopAbs_COMPOUND ) {
689     TDF_Label L = STool->AddShape ( S, Standard_False );
690     ShapeLabelMap.Bind ( S, L );
691     return L;
692   }
693   
694   // for compounds, compute number of subshapes and check whether this is assembly
695   Standard_Boolean isAssembly = Standard_False;
696   Standard_Integer nbComponents = 0;
697   TopoDS_Iterator it;
698   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
699     TopoDS_Shape Sub0 = it.Value();
700     TopLoc_Location loc;
701     Sub0.Location ( loc );
702     if ( NewShapesMap.Contains ( Sub0 ) ) isAssembly = Standard_True;
703   }
704
705 //  if(nbComponents>0) isAssembly = Standard_True;
706   
707   // check whether it has associated external ref
708   TColStd_SequenceOfHAsciiString SHAS;
709   if ( ShapePDMap.IsBound ( S ) && PDFileMap.IsBound ( ShapePDMap.Find(S) ) ) {
710     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( ShapePDMap.Find(S) );
711     if ( ! EF.IsNull() ) {
712       // (store information on extern refs in the document)
713       SHAS.Append(EF->GetName());
714       // if yes, just return corresponding label
715       if ( ! EF->GetLabel().IsNull() ) {
716         // but if components >0, ignore extern ref!
717         if ( nbComponents <=0 ) {
718           ShapeLabelMap.Bind ( S, EF->GetLabel() );
719           STool->SetExternRefs(EF->GetLabel(),SHAS);
720           return EF->GetLabel();
721         }
722       }
723 #ifdef OCCT_DEBUG
724       if ( ! EF->GetLabel().IsNull() )
725         cout << "Warning: STEPCAFControl_Reader::AddShape: Non-empty shape with external ref; ref is ignored" << endl;
726       else if ( nbComponents <=0 ) 
727         cout << "Warning: STEPCAFControl_Reader::AddShape: Result of reading extern ref is Null" << endl;
728 #endif
729     }
730   }
731   
732   // add compound either as a whole,
733   if ( ! isAssembly ) {
734     TDF_Label L = STool->AddShape ( S, Standard_False );
735     if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
736     ShapeLabelMap.Bind ( S, L );
737     return L;
738   }
739   
740   // or as assembly, component-by-component
741   TDF_Label L = STool->NewShape();
742   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
743     TopoDS_Shape Sub0 = it.Value();
744     TopLoc_Location loc;
745     Sub0.Location ( loc );
746     TDF_Label subL = AddShape ( Sub0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
747     if ( ! subL.IsNull() ) {
748       STool->AddComponent ( L, subL, it.Value().Location() );
749     }
750   }
751   if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
752   ShapeLabelMap.Bind ( S, L );
753   //STool->SetShape ( L, S ); // it is necessary for assemblies OCC1747 // commemted by skl for OCC2941
754
755   return L;
756 }
757
758 //=======================================================================
759 //function : ReadExternFile
760 //purpose  : 
761 //=======================================================================
762
763 Handle(STEPCAFControl_ExternFile) STEPCAFControl_Reader::ReadExternFile (const Standard_CString file, 
764                                                                          const Standard_CString fullname, 
765                                                                          Handle(TDocStd_Document)& doc) 
766 {
767   // if the file is already read, associate it with SDR
768   if ( myFiles->HasItem ( file, Standard_True ) ) {
769     return myFiles->Item ( file );
770   }
771
772 #ifdef OCCT_DEBUG
773   cout << "Reading extern file: " << fullname << endl;
774 #endif
775  
776   // create new WorkSession and Reader
777   Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
778   newWS->SelectNorm ( "STEP" );
779   STEPControl_Reader sr ( newWS, Standard_False );
780   
781   // start to fill the resulting ExternFile structure
782   Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
783   EF->SetWS ( newWS );
784   EF->SetName ( new TCollection_HAsciiString ( file ) );
785   
786   // read file
787   EF->SetLoadStatus ( sr.ReadFile ( fullname ) );
788   
789   // transfer in single-result mode
790   if ( EF->GetLoadStatus() == IFSelect_RetDone ) {
791     TDF_LabelSequence labels;
792     EF->SetTransferStatus ( Transfer ( sr, 0, doc, labels, Standard_True ) );
793     if ( labels.Length() >0 ) EF->SetLabel ( labels.Value(1) );
794   }
795   
796   // add read file to dictionary
797   myFiles->SetItem ( file, EF );
798   
799   return EF;
800 }
801
802
803 //=======================================================================
804 //function : SetColorToSubshape
805 //purpose  : auxilary
806 //=======================================================================
807 static void SetColorToSubshape(const Handle(XCAFDoc_ColorTool) & CTool,
808                                const TopoDS_Shape & S,
809                                const Quantity_Color& col,
810                                const XCAFDoc_ColorType type)
811 {
812   for (TopoDS_Iterator it(S); it.More(); it.Next())
813     if (! CTool->SetColor( it.Value(), col, type)) break;
814 }
815
816
817 //=======================================================================
818 //function : findStyledSR
819 //purpose  : auxilary
820 //=======================================================================
821 static void findStyledSR (const Handle(StepVisual_StyledItem) &style,
822                           Handle(StepShape_ShapeRepresentation)& aSR)
823 {
824   // search Shape Represenatation for component styled item
825   for ( Standard_Integer j=1; j <= style->NbStyles(); j++ ) {
826     Handle(StepVisual_PresentationStyleByContext) PSA = 
827       Handle(StepVisual_PresentationStyleByContext)::DownCast(style->StylesValue ( j ));
828     if ( PSA.IsNull() )
829       continue;
830     StepVisual_StyleContextSelect aStyleCntxSlct = PSA->StyleContext();
831     Handle(StepShape_ShapeRepresentation) aCurrentSR = 
832       Handle(StepShape_ShapeRepresentation)::DownCast(aStyleCntxSlct.Representation());
833     if ( aCurrentSR.IsNull() )
834       continue;
835     aSR = aCurrentSR;
836       break;
837   }
838 }
839
840
841 //=======================================================================
842 //function : ReadColors
843 //purpose  : 
844 //=======================================================================
845
846 Standard_Boolean STEPCAFControl_Reader::ReadColors (const Handle(XSControl_WorkSession) &WS,
847                                                     Handle(TDocStd_Document)& Doc,
848                                                     const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
849                                                     const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
850 {
851   STEPConstruct_Styles Styles ( WS );
852   if ( ! Styles.LoadStyles() ) {
853 #ifdef OCCT_DEBUG
854     cout << "Warning: no styles are found in the model" << endl;
855 #endif
856     return Standard_False;
857   }
858   // searching for invisible items in the model
859   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
860   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
861   
862   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
863   if ( CTool.IsNull() ) return Standard_False;
864
865   // parse and search for color attributes
866   Standard_Integer nb = Styles.NbStyles();
867   for ( Standard_Integer i=1; i <= nb; i++ ) {
868     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
869     if ( style.IsNull() ) continue;
870     
871     Standard_Boolean IsVisible = Standard_True;
872     // check the visibility of styled item.
873     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
874       if ( style != aHSeqOfInvisStyle->Value( si ) )
875         continue;
876       // found that current style is invisible.
877       IsVisible = Standard_False;
878       break;
879     }
880
881     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
882     // check if it is component style
883     Standard_Boolean IsComponent = Standard_False;
884     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
885       continue;
886     
887     // find shape
888     TopoDS_Shape S = STEPConstruct::FindShape ( Styles.TransientProcess(), style->Item() );
889     Standard_Boolean isSkipSHUOstyle = Standard_False;
890     // take shape with real location.
891     while ( IsComponent ) {
892       // take SR of NAUO
893       Handle(StepShape_ShapeRepresentation) aSR;
894       findStyledSR( style, aSR );
895       // search for SR along model
896       if (aSR.IsNull())
897         break;
898 //       Handle(Interface_InterfaceModel) Model = WS->Model();
899       Handle(XSControl_TransferReader) TR = WS->TransferReader();
900       Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
901       Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
902       Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
903       for (subs.Start(); subs.More(); subs.Next()) {
904         aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
905         if ( aSDR.IsNull() )
906           continue;
907         StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
908         Handle(StepRepr_ProductDefinitionShape) PDS = 
909           Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
910         if ( PDS.IsNull() )
911           continue;
912         StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
913         
914         Handle(StepRepr_AssemblyComponentUsage) ACU = 
915           Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
916         // PTV 10.02.2003 skip styled item that refer to SHUO
917         if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
918           isSkipSHUOstyle = Standard_True;
919           break;
920         }
921         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
922           Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
923         if ( NAUO.IsNull() )
924           continue;
925         
926         TopoDS_Shape aSh;
927         // PTV 10.02.2003 to find component of assembly CORRECTLY
928         STEPConstruct_Tool Tool( WS );
929         TDF_Label aShLab = FindInstance ( NAUO, CTool->ShapeTool(), Tool, PDFileMap, ShapeLabelMap );
930         aSh = CTool->ShapeTool()->GetShape(aShLab);
931 //         Handle(Transfer_Binder) binder = TP->Find(NAUO);
932 //         if ( binder.IsNull() || ! binder->HasResult() )
933 //           continue;
934 //         aSh = TransferBRep::ShapeResult ( TP, binder );
935         if (!aSh.IsNull()) {
936           S = aSh;
937           break;
938         }
939       }
940       break;
941     }
942     if (isSkipSHUOstyle)
943       continue; // skip styled item which refer to SHUO
944     
945     if ( S.IsNull() )
946       continue;
947     
948     if ( ! SurfCol.IsNull() ) {
949       Quantity_Color col;
950       Styles.DecodeColor ( SurfCol, col );
951       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorSurf ))
952         SetColorToSubshape( CTool, S, col, XCAFDoc_ColorSurf );
953     }
954     if ( ! BoundCol.IsNull() ) {
955       Quantity_Color col;
956       Styles.DecodeColor ( BoundCol, col );
957       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
958         SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
959     }
960     if ( ! CurveCol.IsNull() ) {
961       Quantity_Color col;
962       Styles.DecodeColor ( CurveCol, col );
963       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
964         SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
965     }
966     if ( !IsVisible ) {
967       // sets the invisibility for shape.
968       TDF_Label aInvL;
969       if ( CTool->ShapeTool()->Search( S, aInvL ) )
970         CTool->SetVisibility( aInvL, Standard_False );
971     }
972   }
973   CTool->ReverseChainsOfTreeNodes();
974   return Standard_True;
975 }
976
977 //=======================================================================
978 //function : GetLabelFromPD
979 //purpose  : 
980 //=======================================================================
981
982 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
983                                  const Handle(XCAFDoc_ShapeTool) &STool,
984                                  const Handle(Transfer_TransientProcess) &TP,
985                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
986                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
987 {
988   TDF_Label L;
989   if ( PDFileMap.IsBound ( PD ) ) {
990     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
991     if ( ! EF.IsNull() ) {
992       L = EF->GetLabel();
993       if ( ! L.IsNull() ) return L;
994     }
995   }
996
997   TopoDS_Shape S;
998   Handle(Transfer_Binder) binder = TP->Find(PD);
999   if ( binder.IsNull() || ! binder->HasResult() ) return L;
1000   S = TransferBRep::ShapeResult ( TP, binder );
1001   if ( S.IsNull() ) return L;
1002
1003   if ( S.IsNull() ) return L;
1004   if ( ShapeLabelMap.IsBound ( S ) )
1005     L = ShapeLabelMap.Find ( S );
1006   if ( L.IsNull() )
1007     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1008   return L;
1009 }
1010
1011 //=======================================================================
1012 //function : FindInstance
1013 //purpose  : 
1014 //=======================================================================
1015
1016 TDF_Label STEPCAFControl_Reader::FindInstance (const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
1017                                                const Handle(XCAFDoc_ShapeTool) &STool,
1018                                                const STEPConstruct_Tool &Tool,
1019                                                const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1020                                                const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1021 {
1022   TDF_Label L;
1023   
1024   // get shape resulting from CDSR (in fact, only location is interesting)
1025   Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
1026   Handle(Transfer_Binder) binder = TP->Find(NAUO);
1027   if ( binder.IsNull() || ! binder->HasResult() ) {
1028 #ifdef OCCT_DEBUG
1029     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1030 #endif
1031     return L;
1032   }
1033   
1034   TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1035   if ( S.IsNull() ) {
1036 #ifdef OCCT_DEBUG
1037     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1038 #endif
1039     return L;
1040   }
1041
1042   // find component`s original label
1043   Handle(StepBasic_ProductDefinition) PD = NAUO->RelatedProductDefinition();
1044   if ( PD.IsNull() ) return L;
1045   TDF_Label Lref = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1046   if ( Lref.IsNull() ) return L;
1047   
1048   // find main shape (assembly) label
1049   PD.Nullify();
1050   PD = NAUO->RelatingProductDefinition();
1051   if ( PD.IsNull() ) return L;
1052   TDF_Label L0 = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1053   if ( L0.IsNull() ) return L;
1054   
1055   // if CDSR and NAUO are reversed, swap labels
1056   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1057   Interface_EntityIterator subs1 = Tool.Graph().Sharings(NAUO);
1058   for (subs1.Start(); subs1.More(); subs1.Next()) {
1059     Handle(StepRepr_ProductDefinitionShape) PDS = 
1060       Handle(StepRepr_ProductDefinitionShape)::DownCast(subs1.Value());
1061     if(PDS.IsNull()) continue;
1062     Interface_EntityIterator subs2 = Tool.Graph().Sharings(PDS);
1063     for (subs2.Start(); subs2.More(); subs2.Next()) {
1064       Handle(StepShape_ContextDependentShapeRepresentation) CDSRtmp = 
1065         Handle(StepShape_ContextDependentShapeRepresentation)::DownCast(subs2.Value());
1066       if (CDSRtmp.IsNull()) continue;
1067       CDSR = CDSRtmp;
1068     }
1069   }
1070   if (CDSR.IsNull()) return L;
1071 //  if ( STEPConstruct_Assembly::CheckSRRReversesNAUO ( Tool.Model(), CDSR ) ) {
1072 //    TDF_Label Lsw = L0; L0 = Lref; Lref = Lsw;
1073 //  }
1074   
1075   // iterate on components to find proper one
1076   TDF_LabelSequence seq;
1077   XCAFDoc_ShapeTool::GetComponents ( L0, seq );
1078   for ( Standard_Integer k=1; L.IsNull() && k <= seq.Length(); k++ ) {
1079     TDF_Label Lcomp = seq(k), Lref2;
1080     if ( XCAFDoc_ShapeTool::GetReferredShape ( Lcomp, Lref2 ) && 
1081         Lref2 == Lref &&
1082         S.Location() == XCAFDoc_ShapeTool::GetLocation ( Lcomp ) ) 
1083       L = Lcomp;
1084   }
1085   
1086   return L;
1087 }
1088
1089 //=======================================================================
1090 //function : ReadNames
1091 //purpose  : 
1092 //=======================================================================
1093
1094 Standard_Boolean STEPCAFControl_Reader::ReadNames (const Handle(XSControl_WorkSession) &WS,
1095                                                    Handle(TDocStd_Document)& Doc,
1096                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1097                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1098 {
1099   // get starting data
1100   Handle(Interface_InterfaceModel) Model = WS->Model();
1101   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1102   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1103   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1104   if ( STool.IsNull() ) return Standard_False;
1105   STEPConstruct_Tool Tool ( WS );
1106
1107   // iterate on model to find all SDRs and CDSRs
1108   Standard_Integer nb = Model->NbEntities();
1109   Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
1110   Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
1111   Handle(TCollection_HAsciiString) name;
1112   TDF_Label L;
1113   for (Standard_Integer i = 1; i <= nb; i++) {
1114     Handle(Standard_Transient) enti = Model->Value(i);
1115
1116     // get description of NAUO
1117     if ( enti->DynamicType() == tNAUO ) {
1118       L.Nullify();
1119       Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
1120         Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
1121       if(NAUO.IsNull()) continue;
1122       Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
1123       for (subs.Start(); subs.More(); subs.Next()) {
1124         Handle(StepRepr_ProductDefinitionShape) PDS = 
1125           Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1126         if(PDS.IsNull()) continue;
1127         Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
1128         if ( PDR.IsNull() ) continue;
1129         if ( PDR->HasDescription() && 
1130             PDR->Description()->Length() >0 ) name = PDR->Description();
1131         else if ( !PDR->Name().IsNull() && PDR->Name()->Length() >0 ) name = PDR->Name();
1132         else if ( !PDR->Id().IsNull()) name = PDR->Id();
1133         else name = new TCollection_HAsciiString;
1134       }
1135       // find proper label
1136       L = FindInstance ( NAUO, STool, Tool, PDFileMap, ShapeLabelMap );
1137       if ( L.IsNull() ) continue;
1138       TCollection_ExtendedString str ( name->String() );
1139       TDataStd_Name::Set ( L, str );
1140     }
1141
1142     // for PD get name of associated product
1143     if ( enti->DynamicType() == tPD ) {
1144       L.Nullify();
1145       Handle(StepBasic_ProductDefinition) PD = 
1146         Handle(StepBasic_ProductDefinition)::DownCast(enti);
1147       if(PD.IsNull()) continue;
1148       Handle(StepBasic_Product) Prod = (!PD->Formation().IsNull() ? PD->Formation()->OfProduct() : NULL);
1149       if (Prod.IsNull())
1150         name = new TCollection_HAsciiString;
1151       else if (!Prod->Name().IsNull() && Prod->Name()->UsefullLength() > 0) 
1152         name = Prod->Name();
1153       else if (!Prod->Id().IsNull()) 
1154         name = Prod->Id();
1155       else 
1156         name = new TCollection_HAsciiString;
1157       L = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1158       if ( L.IsNull() ) continue;
1159       TCollection_ExtendedString str ( name->String() );
1160       TDataStd_Name::Set ( L, str );
1161     }
1162     // set a name to the document
1163     //TCollection_ExtendedString str ( name->String() );
1164     //TDataStd_Name::Set ( L, str );
1165   }
1166
1167   return Standard_True;
1168 }
1169
1170 //=======================================================================
1171 //function : GetLabelFromPD
1172 //purpose  : 
1173 //=======================================================================
1174
1175 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1176                                  const Handle(XCAFDoc_ShapeTool) &STool,
1177                                  const STEPConstruct_ValidationProps &Props,
1178                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1179                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1180 {
1181   TDF_Label L;
1182   if ( PDFileMap.IsBound ( PD ) ) {
1183     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1184     if ( ! EF.IsNull() ) {
1185       L = EF->GetLabel();
1186       if ( ! L.IsNull() ) return L;
1187     }
1188   }
1189   TopoDS_Shape S = Props.GetPropShape ( PD );
1190   if ( S.IsNull() ) return L;
1191   if ( ShapeLabelMap.IsBound ( S ) )
1192     L = ShapeLabelMap.Find ( S );
1193   if ( L.IsNull() )
1194     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1195   return L;
1196 }
1197
1198 //=======================================================================
1199 //function : ReadValProps
1200 //purpose  : 
1201 //=======================================================================
1202
1203 Standard_Boolean STEPCAFControl_Reader::ReadValProps (const Handle(XSControl_WorkSession) &WS,
1204                                                       Handle(TDocStd_Document)& Doc,
1205                                                       const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1206                                                       const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1207 {
1208   // get starting data
1209   Handle(Interface_InterfaceModel) Model = WS->Model();
1210   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1211   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1212   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1213   if ( STool.IsNull() ) return Standard_False;
1214
1215   // load props from the STEP model
1216   TColStd_SequenceOfTransient props;
1217   STEPConstruct_ValidationProps Props ( WS );
1218   if ( ! Props.LoadProps ( props ) ) {
1219 #ifdef OCCT_DEBUG
1220     cout << "Warning: no validation props found in the model" << endl;
1221 #endif
1222     return Standard_False;
1223   }
1224
1225   // interpret props one by one
1226   for (Standard_Integer i = 1; i <= props.Length(); i ++) {
1227     Handle(StepRepr_PropertyDefinitionRepresentation) PDR = 
1228       Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast ( props.Value(i) );
1229     if ( PDR.IsNull() ) continue;
1230
1231     TDF_Label L;
1232
1233     Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
1234     Interface_EntityIterator subs = Props.Graph().Shareds(PD);
1235     for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
1236       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)) ) {
1237         Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1238         if(PDS.IsNull()) continue;
1239         // find corresponding NAUO
1240         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
1241         Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
1242         for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
1243           if ( subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)) ) 
1244             NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
1245         }
1246         if ( !NAUO.IsNull() ) {
1247           L = FindInstance ( NAUO, STool, WS, PDFileMap, ShapeLabelMap );
1248           if ( L.IsNull() ) continue;
1249         }
1250         else {
1251           // find corresponding ProductDefinition:
1252           Handle(StepBasic_ProductDefinition) ProdDef;
1253           Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
1254           for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
1255             if ( subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)) ) 
1256               ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
1257           }
1258           if ( ProdDef.IsNull() ) continue;
1259           L = GetLabelFromPD ( ProdDef, STool, Props, PDFileMap, ShapeLabelMap );
1260         }
1261       }
1262
1263       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)) ) {
1264         Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
1265         if(SA.IsNull()) continue;
1266         // find ShapeRepresentation
1267         Handle(StepShape_ShapeRepresentation) SR;
1268         Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
1269         for(subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
1270           Handle(StepRepr_PropertyDefinition) PropD1 = 
1271             Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
1272           if(PropD1.IsNull()) continue;
1273           Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
1274           for(subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
1275             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1276               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
1277             if(SDR.IsNull()) continue;
1278             SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1279           }
1280         }
1281         if(SR.IsNull()) continue;
1282         Handle(Transfer_Binder) binder;
1283         for(Standard_Integer ir=1; ir<=SR->NbItems() && binder.IsNull(); ir++) {
1284           if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
1285             Handle(StepShape_SolidModel) SM = 
1286               Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
1287             binder = TP->Find(SM);
1288           }
1289           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1290             Handle(StepShape_ShellBasedSurfaceModel) SBSM =
1291               Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
1292             binder = TP->Find(SBSM);
1293           }
1294           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1295             Handle(StepShape_GeometricSet) GS =
1296               Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
1297             binder = TP->Find(GS);
1298           }
1299         }
1300         if ( binder.IsNull() || ! binder->HasResult() ) continue;
1301         TopoDS_Shape S;
1302         S = TransferBRep::ShapeResult ( TP, binder );
1303         if(S.IsNull()) continue;
1304         if ( ShapeLabelMap.IsBound ( S ) )
1305           L = ShapeLabelMap.Find ( S );
1306         if ( L.IsNull() )
1307           STool->Search ( S, L, Standard_True, Standard_True, Standard_True );
1308       }
1309     }
1310
1311     if(L.IsNull()) continue;
1312       
1313     // decode validation properties
1314     Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
1315     for ( Standard_Integer j=1; j <= rep->NbItems(); j++ ) {
1316       Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
1317       Standard_Boolean isArea;
1318       Standard_Real val;
1319       gp_Pnt pos;
1320       if ( Props.GetPropReal ( ent, val, isArea ) ) {
1321         if ( isArea ) XCAFDoc_Area::Set ( L, val );
1322         else XCAFDoc_Volume::Set ( L, val );
1323       }
1324       else if ( Props.GetPropPnt ( ent, rep->ContextOfItems(), pos ) ) {
1325         XCAFDoc_Centroid::Set ( L, pos );
1326       }
1327     }
1328   }
1329   return Standard_True;
1330 }
1331
1332 //=======================================================================
1333 //function : ReadLayers
1334 //purpose  : 
1335 //=======================================================================
1336
1337 Standard_Boolean STEPCAFControl_Reader::ReadLayers (const Handle(XSControl_WorkSession) &WS,
1338                                                     Handle(TDocStd_Document)& Doc) const
1339 {
1340   Handle(Interface_InterfaceModel) Model = WS->Model();
1341   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1342   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1343   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1344   if ( STool.IsNull() ) return Standard_False;
1345   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( Doc->Main() );
1346   if ( LTool.IsNull() ) return Standard_False;
1347   
1348   Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
1349   Standard_Integer nb = Model->NbEntities();
1350   Handle(TCollection_HAsciiString) name;
1351   
1352   for (Standard_Integer i = 1; i <= nb; i ++) {
1353     Handle(Standard_Transient) enti = Model->Value(i);
1354     if ( ! enti->IsKind ( tSVPLA ) ) continue;
1355     Handle(StepVisual_PresentationLayerAssignment) SVPLA = 
1356       Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
1357     
1358     Handle(TCollection_HAsciiString) descr = SVPLA->Description();
1359     Handle(TCollection_HAsciiString) hName = SVPLA->Name();
1360     TCollection_ExtendedString aLayerName ( hName->String() );
1361      
1362     // find a target shape and its label in the document
1363     for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++ ) {
1364       StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
1365       Handle(Transfer_Binder) binder = TP->Find( LI.Value() );
1366       if ( binder.IsNull() || ! binder->HasResult() ) continue;
1367       
1368       TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1369       if ( S.IsNull() ) continue;
1370         
1371       TDF_Label shL;
1372       if ( ! STool->Search ( S, shL, Standard_True, Standard_True, Standard_True ) ) continue;
1373       LTool->SetLayer ( shL, aLayerName );
1374     }
1375     
1376     // check invisibility
1377     Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
1378     for (subs.Start(); subs.More(); subs.Next()) {
1379       if ( ! subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility)) ) continue;
1380 #ifdef OCCT_DEBUG
1381       cout<< "\tLayer \"" << aLayerName << "\" is invisible"<<endl;
1382 #endif
1383       //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
1384       TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
1385       Handle(TDataStd_UAttribute) aUAttr;
1386       aUAttr->Set( InvLayerLab, XCAFDoc::InvisibleGUID() );
1387     }
1388   }
1389   return Standard_True;
1390 }
1391
1392 //=======================================================================
1393 //function : ReadSHUOs
1394 //purpose  : 
1395 //=======================================================================
1396
1397 static Standard_Boolean findNextSHUOlevel (const Handle(XSControl_WorkSession) &WS,
1398                                            const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1399                                            const Handle(XCAFDoc_ShapeTool)& STool,
1400                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1401                                            const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1402                                            TDF_LabelSequence& aLabels)
1403 {
1404   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1405   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1406   for (subs.Start(); subs.More(); subs.Next()) {
1407     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1408       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1409       break;
1410     }
1411   }
1412   if (subSHUO.IsNull())
1413     return Standard_False;
1414   
1415   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO =
1416     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subSHUO->NextUsage());
1417   if (NUNAUO.IsNull())
1418     return Standard_False;
1419 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1420 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1421 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1422 //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1423 //   if ( binder.IsNull() || ! binder->HasResult() )
1424 //     return Standard_False;
1425 //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1426   // get label of NAUO next level
1427   TDF_Label NULab;
1428   STEPConstruct_Tool Tool( WS );
1429   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1430 //   STool->Search(NUSh, NUlab);
1431   if (NULab.IsNull())
1432     return Standard_False;
1433   aLabels.Append( NULab );
1434   // and check by recurse.
1435   findNextSHUOlevel( WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels );
1436   return Standard_True;
1437 }
1438
1439
1440 //=======================================================================
1441 //function : setSHUOintoDoc
1442 //purpose  : auxilary
1443 //=======================================================================
1444 static TDF_Label setSHUOintoDoc (const Handle(XSControl_WorkSession) &WS,
1445                                  const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1446                                  const Handle(XCAFDoc_ShapeTool)& STool,
1447                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1448                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1449 {
1450   TDF_Label aMainLabel;
1451   // get upper usage NAUO from SHUO.
1452   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1453     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1454   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO =
1455     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->NextUsage());
1456   if ( UUNAUO.IsNull() || NUNAUO.IsNull() ) {
1457 #ifdef OCCT_DEBUG
1458     cout << "Warning: " << __FILE__ <<": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
1459 #endif
1460     return aMainLabel;
1461   }
1462 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1463 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1464 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1465 //   TopoDS_Shape UUSh, NUSh;
1466 //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1467 //   if ( binder.IsNull() || ! binder->HasResult() )
1468 //     return aMainLabel;
1469 //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1470 //   binder = TP->Find(NUNAUO);
1471 //   if ( binder.IsNull() || ! binder->HasResult() )
1472 //     return aMainLabel;
1473 //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1474
1475   // get first labels for first SHUO attribute
1476   TDF_Label UULab, NULab;
1477   STEPConstruct_Tool Tool( WS );
1478   UULab = STEPCAFControl_Reader::FindInstance ( UUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1479   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1480   
1481 //   STool->Search(UUSh, UULab);
1482 //   STool->Search(NUSh, NULab);
1483   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1484   //create sequence fo labels to set SHUO structure into the document
1485   TDF_LabelSequence ShuoLabels;
1486   ShuoLabels.Append( UULab );
1487   ShuoLabels.Append( NULab );
1488   // add all other labels of sub SHUO entities
1489   findNextSHUOlevel( WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels );
1490   // last accord for SHUO
1491   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1492   if ( STool->SetSHUO( ShuoLabels, anSHUOAttr ) )
1493     aMainLabel = anSHUOAttr->Label();
1494   
1495   return aMainLabel;
1496 }
1497
1498
1499 //=======================================================================
1500 //function : ReadSHUOs
1501 //purpose  : 
1502 //=======================================================================
1503
1504 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs (const Handle(XSControl_WorkSession) &WS,
1505                                                    Handle(TDocStd_Document)& Doc,
1506                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1507                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1508 {
1509   // the big part code duplication from ReadColors.
1510   // It is possible to share this code functionality, just to decide how ???
1511   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
1512   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1513   
1514   STEPConstruct_Styles Styles ( WS );
1515   if ( ! Styles.LoadStyles() ) {
1516 #ifdef OCCT_DEBUG
1517     cout << "Warning: no styles are found in the model" << endl;
1518 #endif
1519     return Standard_False;
1520   }
1521   // searching for invisible items in the model
1522   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1523   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
1524   // parse and search for color attributes
1525   Standard_Integer nb = Styles.NbStyles();
1526   for ( Standard_Integer i=1; i <= nb; i++ ) {
1527     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
1528     if ( style.IsNull() ) continue;
1529     
1530     Standard_Boolean IsVisible = Standard_True;
1531     // check the visibility of styled item.
1532     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
1533       if ( style != aHSeqOfInvisStyle->Value( si ) )
1534         continue;
1535       // found that current style is invisible.
1536 #ifdef OCCT_DEBUG
1537       cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
1538 #endif
1539       IsVisible = Standard_False;
1540       break;
1541     }
1542
1543     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
1544     // check if it is component style
1545     Standard_Boolean IsComponent = Standard_False;
1546     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
1547       continue;
1548     if (!IsComponent)
1549       continue;
1550     Handle(StepShape_ShapeRepresentation) aSR;
1551     findStyledSR( style, aSR );
1552     // search for SR along model
1553     if ( aSR.IsNull() )
1554       continue;
1555     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
1556     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1557     for (subs.Start(); subs.More(); subs.Next()) {
1558       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1559       if ( aSDR.IsNull() )
1560         continue;
1561       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1562       Handle(StepRepr_ProductDefinitionShape) PDS = 
1563         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1564       if ( PDS.IsNull() )
1565         continue;
1566       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1567       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1568         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1569       if ( SHUO.IsNull() )
1570         continue;
1571       
1572       // set the SHUO structure to the document
1573       TDF_Label aLabelForStyle = setSHUOintoDoc( WS, SHUO, STool, PDFileMap, ShapeLabelMap );
1574       if ( aLabelForStyle.IsNull() ) {
1575 #ifdef OCCT_DEBUG
1576         cout << "Warning: " << __FILE__ <<": coudnot create SHUO structure in the document" << endl;
1577 #endif
1578         continue;
1579       }
1580       // now set the style to the SHUO main label.
1581       if ( ! SurfCol.IsNull() ) {
1582         Quantity_Color col;
1583         Styles.DecodeColor ( SurfCol, col );
1584         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorSurf );
1585       }
1586       if ( ! BoundCol.IsNull() ) {
1587         Quantity_Color col;
1588         Styles.DecodeColor ( BoundCol, col );
1589         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1590       }
1591       if ( ! CurveCol.IsNull() ) {
1592         Quantity_Color col;
1593         Styles.DecodeColor ( CurveCol, col );
1594         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1595       }
1596       if ( !IsVisible )
1597         // sets the invisibility for shape.
1598         CTool->SetVisibility( aLabelForStyle, Standard_False );
1599       
1600     } // end search SHUO by SDR
1601   } // end iterates on styles
1602       
1603   return Standard_True;
1604 }
1605
1606
1607 //=======================================================================
1608 //function : GetLengthConversionFactor
1609 //purpose  : 
1610 //=======================================================================
1611 static Standard_Boolean GetLengthConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1612                                                   Standard_Real& afact)
1613 {
1614   afact=1.;
1615   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit)) ) return Standard_False;
1616   Handle(StepBasic_ConversionBasedUnitAndLengthUnit) CBULU =
1617     Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(NU);
1618   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1619   afact = MWUCBU->ValueComponent();
1620   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1621   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1622     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1623     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1624       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1625       if(SU->Name()==StepBasic_sunMetre) {
1626         if(SU->HasPrefix()) 
1627           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1628         // convert m to mm
1629         afact *= 1000.;
1630       }
1631     }
1632   }
1633   return Standard_True;
1634 }
1635
1636
1637 //=======================================================================
1638 //function : GetAngleConversionFactor
1639 //purpose  : 
1640 //=======================================================================
1641 static Standard_Boolean GetAngleConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1642                                                   Standard_Real& afact)
1643 {
1644   afact=1.;
1645   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)) ) return Standard_False;
1646   Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit) CBULU =
1647     Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)::DownCast(NU);
1648   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1649   afact = MWUCBU->ValueComponent();
1650   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1651   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1652     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1653     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1654       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1655       if(SU->Name()==StepBasic_sunRadian) {
1656         if(SU->HasPrefix()) 
1657           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1658         // convert radian to deg
1659         afact *= 180/M_PI;
1660       }
1661     }
1662   }
1663   return Standard_True;
1664 }
1665
1666 //=======================================================================
1667 //function : GetMassConversionFactor
1668 //purpose  : 
1669 //=======================================================================
1670 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1671                                                 Standard_Real& afact)
1672 {
1673   afact=1.;
1674   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit)) ) return Standard_False;
1675   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1676     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1677   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1678   afact = MWUCBU->ValueComponent();
1679   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1680   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1681     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1682     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1683       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1684       if(SU->Name()==StepBasic_sunGram) {
1685         if(SU->HasPrefix())
1686           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1687       }
1688     }
1689   }
1690   return Standard_True;
1691 }
1692
1693
1694 //=======================================================================
1695 //function : ReadDatums
1696 //purpose  : auxilary
1697 //=======================================================================
1698 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
1699                                    const Handle(XCAFDoc_DimTolTool) &DGTTool,
1700                                    const Interface_Graph &graph,
1701                                    Handle(Transfer_TransientProcess) &TP,
1702                                    const TDF_Label TolerL,
1703                                    const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
1704 {
1705   if(GTWDR.IsNull()) return Standard_False;
1706   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
1707   if(HADR.IsNull()) return Standard_False;
1708   for(Standard_Integer idr=1; idr<=HADR->Length(); idr++) {
1709     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
1710     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
1711     if(aDatum.IsNull()) continue;
1712     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
1713     for(subs4.Start(); subs4.More(); subs4.Next()) {
1714       Handle(StepRepr_ShapeAspectRelationship) SAR = 
1715         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
1716       if(SAR.IsNull()) continue;
1717       Handle(StepDimTol_DatumFeature) DF = 
1718         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
1719       if(DF.IsNull()) continue;
1720       Interface_EntityIterator subs5 = graph.Sharings(DF);
1721       Handle(StepRepr_PropertyDefinition) PropDef;
1722       for(subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
1723         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
1724       }
1725       if(PropDef.IsNull()) continue;
1726       Handle(StepShape_AdvancedFace) AF;
1727       subs5 = graph.Sharings(PropDef);
1728       for(subs5.Start(); subs5.More(); subs5.Next()) {
1729         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
1730           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
1731         if(!SDR.IsNull()) {
1732           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
1733           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
1734             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
1735             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
1736           }
1737         }
1738       }
1739       if(AF.IsNull()) return Standard_False;
1740       Standard_Integer index = TP->MapIndex(AF);
1741       TopoDS_Shape aSh;
1742       if(index >0) {
1743         Handle(Transfer_Binder) binder = TP->MapItem(index);
1744         aSh = TransferBRep::ShapeResult(binder);
1745       }
1746       if(aSh.IsNull()) continue; 
1747       TDF_Label shL;
1748       if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
1749       DGTTool->SetDatum(shL,TolerL,PropDef->Name(),PropDef->Description(),aDatum->Identification());
1750     }
1751   }
1752   return Standard_True;
1753 }
1754
1755
1756 //=======================================================================
1757 //function : setDatumToXCAF
1758 //purpose  : 
1759 //=======================================================================
1760 static Standard_Boolean setDatumToXCAF(const Handle(StepDimTol_Datum)& theDat,
1761                                         const TDF_Label theGDTL,
1762                                         const Standard_Integer thePositionCounter,
1763                                         const XCAFDimTolObjects_DatumModifiersSequence& aXCAFModifiers,
1764                                         const XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal,
1765                                         const Standard_Real aModifValue,
1766                                         const Handle(TDocStd_Document)& theDoc,
1767                                         const Handle(XSControl_WorkSession)& theWS)
1768 {
1769   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
1770   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
1771   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
1772   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
1773   const Interface_Graph& aGraph = aTP->Graph();
1774   Handle(XCAFDoc_Datum) aDat;
1775   TDF_Label aShL;
1776   Standard_Boolean aRefShapeIsFound = Standard_False;
1777   Standard_Boolean aFirstStep = Standard_True;
1778   Interface_EntityIterator anIterD = aGraph.Sharings(theDat);
1779   for(anIterD.Start(); anIterD.More(); anIterD.Next()) {
1780     Handle(StepRepr_ShapeAspectRelationship) aSAR = 
1781       Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterD.Value());
1782     if(aSAR.IsNull()) continue;
1783
1784     Handle(StepRepr_ShapeAspect) aSA = aSAR->RelatingShapeAspect();
1785     if (aSA.IsNull()) continue;
1786     Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
1787     if(aSA->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
1788     {
1789       //processing for complex entity
1790       Interface_EntityIterator anIterC = aGraph.Sharings(aSA);
1791       for(anIterC.Start(); anIterC.More(); anIterC.Next()) {
1792         Handle(StepRepr_ShapeAspectRelationship) SAR = 
1793           Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterC.Value());
1794         if(SAR.IsNull()) continue;
1795         Handle(StepRepr_ShapeAspect) aS = 
1796           Handle(StepRepr_ShapeAspect)::DownCast(SAR->RelatedShapeAspect());
1797         if(aS.IsNull()) continue;
1798         Interface_EntityIterator anIterSA = aGraph.Sharings(aS);
1799         for(anIterSA.Start(); anIterSA.More() && aPGISU.IsNull(); anIterSA.Next()) {
1800           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
1801         }
1802         if(!aPGISU.IsNull()){
1803           aSA = aS;
1804           break;
1805         }
1806       }
1807     }
1808     else if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
1809     {
1810       //processing for datum target
1811       Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
1812       for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
1813         if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_FeatureForDatumTargetRelationship)))
1814         {
1815           Interface_EntityIterator anIterFFD = aGraph.Shareds(anIterDTF.Value());
1816           for(anIterFFD.Start(); anIterFFD.More(); anIterFFD.Next()) {
1817             if(anIterFFD.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
1818             {
1819               aSA = Handle(StepRepr_ShapeAspect)::DownCast(anIterFFD.Value());
1820             }
1821           }
1822         }
1823       }
1824     }
1825     if (aSA.IsNull()) continue;
1826     Interface_EntityIterator anIterDSWP = aGraph.Sharings(aSA);
1827     for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
1828       aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
1829     }
1830     if(aPGISU.IsNull()) continue;
1831     // get representation item
1832     Handle(StepRepr_RepresentationItem) aRI;
1833     for(Standard_Integer i = 1 ; i <= aPGISU->NbIdentifiedItem() && aRI.IsNull(); i++)
1834     {
1835       aRI = Handle(StepRepr_RepresentationItem)::DownCast(aPGISU->IdentifiedItemValue(i));
1836     }
1837     if(aRI.IsNull()) continue;
1838     Standard_Integer index = aTP->MapIndex(aRI);
1839     TopoDS_Shape aSh;
1840     if(index >0) {
1841       Handle(Transfer_Binder) binder = aTP->MapItem(index);
1842       aSh = TransferBRep::ShapeResult(binder);
1843     }
1844     if(aSh.IsNull()) continue; 
1845     if( !aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True) ) continue;
1846     Handle(TDataStd_TreeNode) aNode;
1847     if(aFirstStep && aShL.FindAttribute(XCAFDoc::DatumRefGUID(),aNode) && aNode->HasFirst() &&
1848        aNode->First()->Label().FindAttribute(XCAFDoc_Datum::GetID(),aDat))
1849     {
1850       //if datums already attached, not need add datum target
1851       aRefShapeIsFound = Standard_True;
1852     }
1853     aFirstStep = Standard_False;
1854     Handle(XCAFDimTolObjects_DatumObject) aDatObj;
1855     if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
1856     {
1857       if(!aRefShapeIsFound)
1858       {
1859         //if datum targers not yet added
1860         TDF_Label aDatL = aDGTTool->AddDatum();
1861         aDat = XCAFDoc_Datum::Set(aDatL);
1862         aDGTTool->SetDatum(aShL, aDatL);
1863         aDatObj = aDat->GetObject();
1864         aDatObj->SetName(theDat->Identification());
1865         aDatObj->IsDatumTarget(Standard_True);
1866         XCAFDimTolObjects_DatumTargetType aType;
1867         if(STEPConstruct_GDTProperty::GetDatumTargetType(aSA->Description(),aType))
1868         {
1869           aDatObj->SetDatumTargetType(aType);
1870           if(aType == XCAFDimTolObjects_DatumTargetType_Area)
1871           {
1872             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
1873             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
1874               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
1875               {
1876                 Handle(StepAP242_GeometricItemSpecificUsage) aGISU
1877                   = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
1878                 Handle(StepRepr_RepresentationItem) anItem;
1879                 if(aPGISU->NbIdentifiedItem() > 0) {
1880                   anItem = Handle(StepRepr_RepresentationItem)::DownCast(aPGISU->IdentifiedItemValue(1));
1881                 }
1882                 if(anItem.IsNull()) continue;
1883                 Standard_Integer anItemIndex = aTP->MapIndex(anItem);
1884                 if(anItemIndex >0) {
1885                   Handle(Transfer_Binder) binder = aTP->MapItem(anItemIndex);
1886                   TopoDS_Shape anItemShape = TransferBRep::ShapeResult(binder);
1887                   aDatObj->SetDatumTarget(anItemShape);
1888                 }
1889               }
1890             }
1891           }
1892           else
1893           {
1894             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
1895             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
1896               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_PropertyDefinition)))
1897               {
1898                 Interface_EntityIterator anIterPD = aGraph.Shareds(anIterDTF.Value());
1899                 for(anIterPD.Start(); anIterPD.More(); anIterPD.Next()) {
1900                   if(anIterPD.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
1901                   {
1902                     Interface_EntityIterator anIterSDR = aGraph.Sharings(anIterPD.Value());
1903                     for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) {
1904                       if(anIterSDR.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeRepresentationWithParameters)))
1905                       {
1906                         Handle(StepShape_ShapeRepresentationWithParameters) aSRWP
1907                           = Handle(StepShape_ShapeRepresentationWithParameters)::DownCast(anIterSDR.Value());
1908                         for(Standard_Integer r = aSRWP->Items()->Lower(); r <= aSRWP->Items()->Upper(); r++)
1909                         {
1910                           if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
1911                           {
1912                             Handle(StepGeom_Axis2Placement3d) anAx
1913                               = Handle(StepGeom_Axis2Placement3d)::DownCast(aSRWP->ItemsValue(r));
1914                             Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
1915                             Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
1916                             Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
1917                             gp_Dir aDir;
1918                             gp_Dir aDirR;
1919                             gp_Pnt aPnt;
1920                             if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
1921                               !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
1922                               !aLocArr.IsNull() && aLocArr->Length() > 2)
1923                             {
1924                               aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
1925                               aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
1926                               aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
1927                               gp_Ax2 anA(aPnt, aDir, aDirR);
1928                               aDatObj->SetDatumTargetAxis(anA);
1929                             }
1930                           }
1931                           else if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit)))
1932                           {
1933                             Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aM =
1934                               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aSRWP->ItemsValue(r)); 
1935                             Standard_Real aVal = aM->GetMeasureWithUnit()->ValueComponent();
1936                             StepBasic_Unit anUnit = aM->GetMeasureWithUnit()->UnitComponent();
1937                             Standard_Real aFact=1.;
1938                             if(anUnit.IsNull()) continue;
1939                             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
1940                             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
1941                             if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
1942                             if(aM->Name()->String().IsEqual("target length") ||
1943                               aM->Name()->String().IsEqual("target diameter"))
1944                               aDatObj->SetDatumTargetLength(aVal);
1945                             else
1946                               aDatObj->SetDatumTargetWidth(aVal);
1947                           }
1948                         }
1949                       }
1950                     }
1951                   }
1952                 }
1953               }
1954             }
1955           }
1956         }
1957       }
1958     }
1959     else
1960     {
1961       //processing for darum feature
1962       TDF_Label aDatL = aDGTTool->AddDatum();
1963       aDat = XCAFDoc_Datum::Set(aDatL);
1964       aDGTTool->SetDatum(aShL, aDatL);
1965       aDatObj = aDat->GetObject();
1966       aDatObj->SetName(theDat->Identification());
1967       aDatObj->SetPosition (thePositionCounter);
1968       if(!aXCAFModifiers.IsEmpty())
1969         aDatObj->SetModifiers(aXCAFModifiers);
1970       if (aXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None) 
1971         aDatObj->SetModifierWithValue(aXCAFModifWithVal, aModifValue);
1972       aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
1973     }
1974     if(!aDatObj.IsNull())
1975       aDat->SetObject(aDatObj);
1976   }
1977   return !aDat.IsNull();
1978 }
1979
1980
1981 //=======================================================================
1982 //function : ReadDatums
1983 //purpose  : auxilary
1984 //=======================================================================
1985 static Standard_Boolean readDatumsAP242(const Handle(Standard_Transient)& theEnt,
1986                                         const TDF_Label theGDTL,
1987                                         const Handle(TDocStd_Document)& theDoc,
1988                                         const Handle(XSControl_WorkSession)& theWS)
1989 {
1990   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
1991   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
1992   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
1993   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
1994   const Interface_Graph& aGraph = aTP->Graph();
1995
1996   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
1997   for(anIter.Start(); anIter.More(); anIter.Next()) {
1998     Handle(Standard_Transient) anAtr = anIter.Value();
1999     if(anAtr->IsKind(STANDARD_TYPE(StepDimTol_DatumSystem)))
2000     {
2001       Standard_Integer aPositionCounter = 0;//position on frame 
2002       Handle(StepDimTol_DatumSystem) aDS = Handle(StepDimTol_DatumSystem)::DownCast(anAtr);
2003       Interface_EntityIterator anIterDS = aGraph.Sharings(aDS);
2004       for(anIterDS.Start(); anIterDS.More(); anIterDS.Next()) {
2005         Handle(Standard_Transient) anAtrDS = anIterDS.Value();
2006         if(anAtrDS->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2007         {
2008           //get axis
2009           Handle(StepAP242_GeometricItemSpecificUsage)aAxGISUI
2010             = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anAtrDS);
2011           if (aAxGISUI->IdentifiedItemValue(1)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2012           {
2013             Handle(StepGeom_Axis2Placement3d) anAx
2014               = Handle(StepGeom_Axis2Placement3d)::DownCast(aAxGISUI->IdentifiedItemValue(1));
2015             Handle(XCAFDoc_GeomTolerance) aTol;
2016             if(theGDTL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aTol))
2017             {
2018               Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aTol->GetObject();
2019               Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2020               Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2021               Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2022               gp_Dir aDir;
2023               gp_Dir aDirR;
2024               gp_Pnt aPnt;
2025               if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2026                 !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2027                 !aLocArr.IsNull() && aLocArr->Length() > 2)
2028               {
2029                 aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2030                 aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2031                 aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2032                 gp_Ax2 anA(aPnt, aDir, aDirR);
2033                 anObj->SetAxis(anA);
2034                 aTol->SetObject(anObj);
2035               }
2036             }
2037           }
2038         }
2039       }
2040       if (aDS->NbConstituents() > 0)
2041       {
2042         //get datum feature and datum target from datum system
2043         Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aDRCA = aDS->Constituents();
2044         if(!aDRCA.IsNull())
2045         {
2046           for(Standard_Integer i = aDRCA->Lower(); i <= aDRCA->Upper(); i++)
2047           {
2048             Handle(StepDimTol_DatumReferenceCompartment) aDRC
2049               = Handle(StepDimTol_DatumReferenceCompartment)::DownCast(aDRCA->Value(i));
2050             //gete modifiers
2051             Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModif = aDRC->Modifiers();
2052             XCAFDimTolObjects_DatumModifiersSequence aXCAFModifiers;
2053             XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal = XCAFDimTolObjects_DatumModifWithValue_None;
2054             Standard_Real aModifValue = 0;
2055             if(!aModif.IsNull())
2056             {
2057               for(Standard_Integer m = aModif->Lower(); m <= aModif->Upper(); m++)
2058               {
2059                 if(aModif->Value(m).CaseNumber() == 2)
2060                   aXCAFModifiers.Append(
2061                   (XCAFDimTolObjects_DatumSingleModif)aModif->Value(m).
2062                   SimpleDatumReferenceModifierMember()->Value());
2063                 else if (aModif->Value(m).CaseNumber() == 1)
2064                 {
2065                   aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModif->Value(m).DatumReferenceModifierWithValue()->ModifierType() + 1);
2066                   Standard_Real aVal = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2067                   StepBasic_Unit anUnit = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2068                   Standard_Real aFact=1.;
2069                   if(anUnit.IsNull()) continue;
2070                   if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2071                   Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2072                   if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2073                   aModifValue = aVal;
2074                 }
2075               }
2076             }
2077             aPositionCounter++;
2078             Interface_EntityIterator anIterDRC = aGraph.Shareds(aDRC);
2079             for(anIterDRC.Start(); anIterDRC.More(); anIterDRC.Next()) {
2080               
2081               if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2082               {
2083                 Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRC.Value());
2084                 setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2085               }
2086               else if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_DatumReferenceElement)))
2087               {
2088                 Handle(StepDimTol_DatumReferenceElement) aDRE 
2089                   = Handle(StepDimTol_DatumReferenceElement)::DownCast(anIterDRC.Value());
2090                 //get modifiers from group of datums
2091                 Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifE = aDRE->Modifiers();
2092                 if(!aModifE.IsNull())
2093                 {
2094                   for(Standard_Integer k = aModifE->Lower(); k <= aModifE->Upper(); k++)
2095                   {
2096                     if(aModifE->Value(k).CaseNumber() == 1)
2097                       aXCAFModifiers.Append(
2098                       (XCAFDimTolObjects_DatumSingleModif)aModifE->Value(k).
2099                       SimpleDatumReferenceModifierMember()->Value());
2100                     else if (aModifE->Value(k).CaseNumber() == 2)
2101                     {
2102                       aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierType() + 1);
2103                       Standard_Real aVal = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2104                       StepBasic_Unit anUnit = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2105                       Standard_Real aFact=1.;
2106                       if(anUnit.IsNull()) continue;
2107                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2108                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2109                       if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2110                       aModifValue = aVal;
2111                     }
2112                   }
2113                 }
2114                 Interface_EntityIterator anIterDRE = aGraph.Shareds(aDRE);
2115                 for(anIterDRE.Start(); anIterDRE.More(); anIterDRE.Next()) {
2116                   if(anIterDRE.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2117                   {
2118                     Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRE.Value());
2119                     setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2120                   }
2121                 }
2122               }
2123             }
2124           }
2125         }
2126       }
2127     }
2128   }
2129   return Standard_True;
2130 }
2131
2132 //=======================================================================
2133 //function : craeteGeomTolObjectInXCAF
2134 //purpose  : 
2135 //=======================================================================
2136 static TDF_Label createGDTObjectInXCAF(const Handle(Standard_Transient)& theEnt,
2137                                                const Handle(TDocStd_Document)& theDoc,
2138                                                const Handle(XSControl_WorkSession)& theWS)
2139 {
2140   TDF_Label aGDTL;
2141   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2142      !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) && 
2143      !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2144   {
2145     return aGDTL;
2146   }
2147
2148   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2149   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2150   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2151   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2152   const Interface_Graph& aGraph = aTP->Graph();
2153   Standard_Boolean isAllAround = Standard_False;
2154   Standard_Boolean isAllOver = Standard_False;
2155   
2156   // find RepresentationItem for current Ent
2157   NCollection_Sequence<Handle(Standard_Transient)> aSeqRI1, aSeqRI2;
2158
2159   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2160   for(anIter.Start(); anIter.More(); anIter.Next()) {
2161     Handle(Standard_Transient) anAtr = anIter.Value();
2162     NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2163     if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)))
2164     {
2165       //if associating tolerances with part (All-Over)
2166       Interface_EntityIterator anIterSDR = aGraph.Sharings(anAtr);
2167       for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) 
2168       {
2169         Handle(Standard_Transient) anAtrSDR = anIterSDR.Value();
2170         if(anAtrSDR->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2171         {
2172           isAllOver = Standard_True;
2173           Interface_EntityIterator anIterABSR = aGraph.Shareds(anAtrSDR);
2174           for(anIterABSR.Start(); anIterABSR.More(); anIterABSR.Next()) 
2175           {
2176             Handle(Standard_Transient) anAtrABSR = anIterABSR.Value();
2177             if(anAtrABSR->IsKind(STANDARD_TYPE(StepShape_AdvancedBrepShapeRepresentation)))
2178             {
2179               aSeqRI1.Append(anAtrABSR);
2180             }
2181           }
2182         }
2183       }
2184     }
2185     else if(anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) || 
2186       anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2187     {
2188       //if tolerance attached to dimension
2189       Interface_EntityIterator anIterDim = aGraph.Shareds(anAtr);
2190       for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) 
2191       {
2192         Handle(Standard_Transient) anAtrDim = anIterDim.Value();
2193         if(anAtrDim->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2194           anAtrDim->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2195         {
2196           Interface_EntityIterator anIterCSA = aGraph.Sharings(anAtrDim);
2197           for(anIterCSA.Start(); anIterCSA.More(); anIterCSA.Next()) {
2198             if (anIterCSA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2199               Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterCSA.Value());
2200               for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2201                 if (anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))){
2202                   aSAs.Append(Handle(StepRepr_ShapeAspect)::DownCast(anIterSAR.Value()));
2203                 }
2204               }
2205             }
2206           }
2207         }
2208         else if(anAtrDim->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2209         {
2210           aSAs.Append( Handle(StepRepr_ShapeAspect)::DownCast(anAtrDim));
2211         }
2212       }
2213     }
2214     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2215       anAtr->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2216     {
2217       //processing for composite entity
2218       Handle(Standard_Transient) anAtrTmp = anAtr;
2219       if(anAtr->IsKind(STANDARD_TYPE(StepRepr_AllAroundShapeAspect)))
2220       {
2221         // if applyed AllAround Modifier
2222         isAllAround = Standard_True;
2223         Interface_EntityIterator anIterAASA = aGraph.Sharings(anAtrTmp);
2224         for(anIterAASA.Start(); anIterAASA.More(); anIterAASA.Next()) {
2225           if (anIterAASA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2226             Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterAASA.Value());
2227             for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2228               if ((anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2229                 anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp))) &&
2230                 anAtrTmp != anIterSAR.Value()){
2231                   anAtrTmp = anIterSAR.Value();
2232                   break;
2233               }
2234             }
2235           }
2236         }
2237       }
2238       Interface_EntityIterator anIterCSA = aGraph.Sharings(anAtrTmp);
2239       for(anIterCSA.Start(); anIterCSA.More(); anIterCSA.Next()) {
2240         if (anIterCSA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2241           Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterCSA.Value());
2242           for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2243             if (anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))){
2244               aSAs.Append(Handle(StepRepr_ShapeAspect)::DownCast(anIterSAR.Value()));
2245             }
2246           }
2247         }
2248       }
2249     }
2250     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2251     {
2252       //default
2253       aSAs.Append( Handle(StepRepr_ShapeAspect)::DownCast(anAtr));
2254     }
2255     if(!aSAs.IsEmpty())
2256     {
2257       //get representation items
2258       NCollection_Sequence<Handle(Standard_Transient)> aSeqRI;
2259       for(Standard_Integer i = aSAs.Lower(); i <= aSAs.Upper(); i++)
2260       {
2261         Interface_EntityIterator anIterSA = aGraph.Sharings(aSAs.Value(i));
2262         Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2263         Handle(StepRepr_PropertyDefinition) PropD;
2264         for(anIterSA.Start(); anIterSA.More() && aGISU.IsNull() && PropD.IsNull(); anIterSA.Next()) {
2265           aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2266           PropD = Handle(StepRepr_PropertyDefinition)::DownCast(anIterSA.Value());
2267         }
2268         if(!PropD.IsNull())//for old version
2269         {
2270           Handle(StepRepr_RepresentationItem) RI;
2271           Interface_EntityIterator subs4 = aGraph.Sharings(PropD);
2272           for(subs4.Start(); subs4.More(); subs4.Next()) {
2273             Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2274               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
2275             if(!SDR.IsNull()) {
2276               Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2277               if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2278                 RI = Repr->ItemsValue(1);
2279               }
2280             }
2281           }
2282           if(RI.IsNull()) continue;
2283
2284           if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2285             // read dimensions
2286             Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
2287             if(EC.IsNull()) continue;
2288             Handle(TCollection_HAsciiString) aName;
2289             Handle(StepShape_DimensionalSize) DimSize = 
2290               Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2291             Standard_Real dim1=-1.,dim2=-1.;
2292             subs4 = aGraph.Sharings(DimSize);
2293             for(subs4.Start(); subs4.More(); subs4.Next()) {
2294               Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR = 
2295                 Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
2296               if(!DimCharR.IsNull()) {
2297                 Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
2298                 if(!SDimR.IsNull() && SDimR->NbItems()>0) {
2299                   Handle(StepRepr_RepresentationItem) anItem = SDimR->ItemsValue(1);
2300                   Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(anItem);
2301                   if(!VR.IsNull()) {
2302                     aName = VR->Name();
2303                     //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
2304                     //if(CID.IsNull()) continue;
2305                     //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
2306                     //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
2307                     //if(CIDM.IsNull()) continue;
2308                     //if(CIDM->ArrTransient().IsNull()) continue;
2309                     //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
2310                     //if(CID.CaseMem(CIDM)==1)
2311                     //  HARI = CID.ListRepresentationItem();
2312                     //if(CID.CaseMem(CIDM)==2)
2313                     //  HARI = CID.SetRepresentationItem();
2314                     Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
2315                     if(HARI.IsNull()) continue;
2316                     if(HARI->Length()>0) {
2317                       Handle(StepRepr_RepresentationItem) RI1 =
2318                         Handle(StepRepr_RepresentationItem)::DownCast(HARI->Value(1));
2319                       if(RI1.IsNull()) continue;
2320                       if(RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2321                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2322                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
2323                         dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2324                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2325                         Standard_Real afact=1.;
2326                         if(anUnit.IsNull()) continue;
2327                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2328                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2329                         if(GetLengthConversionFactor(NU,afact)) dim1=dim1*afact;
2330                       }
2331                     }
2332                     if(HARI->Length()>1) {
2333                       Handle(StepRepr_RepresentationItem) RI2 =
2334                         Handle(StepRepr_RepresentationItem)::DownCast(HARI->Value(2));
2335                       if(RI2.IsNull()) continue;
2336                       if(RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2337                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2338                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
2339                         dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2340                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2341                         Standard_Real afact=1.;
2342                         if(anUnit.IsNull()) continue;
2343                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2344                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2345                         if(GetLengthConversionFactor(NU,afact)) dim2 = dim2*afact;
2346                       }
2347                     }
2348                   }
2349                 }
2350               }
2351             }
2352             if(dim1<0) continue;
2353             if(dim2<0) dim2=dim1;
2354             //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
2355             // now we know edge_curve and value range therefore
2356             // we can create corresponding D&GT labels
2357             Standard_Integer index = aTP->MapIndex(EC);
2358             TopoDS_Shape aSh;
2359             if(index >0) {
2360               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2361               aSh = TransferBRep::ShapeResult(binder);
2362             }
2363             if(aSh.IsNull()) continue; 
2364             TDF_Label shL;
2365             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2366             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,2);
2367             arr->SetValue(1,dim1);
2368             arr->SetValue(2,dim2);
2369             aDGTTool->SetDimTol(shL,1,arr,aName,DimSize->Name());
2370           }
2371           // read tolerances and datums
2372           else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2373             Handle(StepDimTol_GeometricTolerance) GT =
2374               Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2375             // read common data for tolerance
2376             //Standard_Real dim = GT->Magnitude()->ValueComponent();
2377             Handle (StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
2378             if(dim3.IsNull()) continue;
2379             Standard_Real dim = dim3->ValueComponent();
2380             StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
2381             Standard_Real afact=1.;
2382             if(anUnit.IsNull()) continue;
2383             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2384             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2385             if(GetLengthConversionFactor(NU,afact)) dim = dim*afact;
2386             //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
2387             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,1);
2388             arr->SetValue(1,dim);
2389             Handle(TCollection_HAsciiString) aName = GT->Name();
2390             Handle(TCollection_HAsciiString) aDescription = GT->Description();
2391             Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2392             if(AF.IsNull()) continue;
2393             Standard_Integer index = aTP->MapIndex(AF);
2394             TopoDS_Shape aSh;
2395             if(index >0) {
2396               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2397               aSh = TransferBRep::ShapeResult(binder);
2398             }
2399             if(aSh.IsNull()) continue; 
2400             TDF_Label shL;
2401             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2402             // read specific data for tolerance
2403             if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
2404               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2405                 Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(theEnt);
2406               Standard_Integer kind=20;
2407               Handle(StepDimTol_ModifiedGeometricTolerance) MGT = 
2408                 GTComplex->GetModifiedGeometricTolerance();
2409               if(!MGT.IsNull()) {
2410                 kind = kind + MGT->Modifier()+1;
2411               }
2412               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2413               // translate datums connected with this tolerance
2414               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2415                 GTComplex->GetGeometricToleranceWithDatumReference();
2416               if(!GTWDR.IsNull()) {
2417                 ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2418               }
2419             }
2420             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
2421               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2422                 Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(theEnt);
2423               if(GTWDR.IsNull()) continue;
2424               Standard_Integer kind = 0;
2425               if     (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
2426               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
2427               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
2428               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
2429               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
2430               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
2431               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
2432               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
2433               //cout<<"GTWDR: kind="<<kind<<endl;
2434               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2435               ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2436             }
2437             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
2438               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2439                 Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(theEnt);
2440               Standard_Integer kind = 35 + MGT->Modifier();
2441               aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2442             }
2443             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
2444               aDGTTool->SetDimTol(shL,38,arr,aName,aDescription);
2445             }
2446             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
2447               aDGTTool->SetDimTol(shL,39,arr,aName,aDescription);
2448             }
2449             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
2450               aDGTTool->SetDimTol(shL,40,arr,aName,aDescription);
2451             }
2452             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
2453               aDGTTool->SetDimTol(shL,41,arr,aName,aDescription);
2454             }
2455             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
2456               aDGTTool->SetDimTol(shL,42,arr,aName,aDescription);
2457             }
2458             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
2459               aDGTTool->SetDimTol(shL,43,arr,aName,aDescription);
2460             }
2461             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
2462               aDGTTool->SetDimTol(shL,44,arr,aName,aDescription);
2463             }
2464           }
2465         }
2466         else
2467         {
2468           if(aGISU.IsNull()) continue;
2469           if(aGISU->NbIdentifiedItem() > 0) {
2470             aSeqRI.Append(aGISU->IdentifiedItemValue(1));
2471           }
2472         }
2473       }
2474       if(!aSeqRI.IsEmpty())
2475       {
2476         if(aSeqRI1.IsEmpty())
2477           aSeqRI1 = aSeqRI;
2478         else 
2479           aSeqRI2 = aSeqRI;
2480       }
2481     }
2482   }
2483   if(aSeqRI1.IsEmpty()) return aGDTL;
2484
2485   TDF_LabelSequence aShLS1, aShLS2;
2486
2487   for(Standard_Integer i = aSeqRI1.Lower(); i <= aSeqRI1.Upper() ;i++)
2488   {
2489     Standard_Integer anIndex = aTP->MapIndex(aSeqRI1.Value(i));
2490     TopoDS_Shape aSh;
2491     if(anIndex >0) {
2492       Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2493       aSh = TransferBRep::ShapeResult(aBinder);
2494     }
2495     if(!aSh.IsNull())
2496     {
2497       TDF_Label aShL;
2498       aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2499       aShLS1.Append(aShL);
2500     }
2501   }
2502   if (!aSeqRI2.IsEmpty())
2503   {
2504     //for dimensional location
2505     for(Standard_Integer i = aSeqRI2.Lower(); i <= aSeqRI2.Upper() ;i++)
2506     {
2507       Standard_Integer anIndex = aTP->MapIndex(aSeqRI2.Value(i));
2508       TopoDS_Shape aSh;
2509       if(anIndex >0) {
2510         Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2511         aSh = TransferBRep::ShapeResult(aBinder);
2512       }
2513       if(!aSh.IsNull())
2514       {
2515         TDF_Label aShL;
2516         aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2517         aShLS2.Append(aShL);
2518       }
2519     }
2520   }
2521
2522   if(!aShLS1.IsEmpty())
2523   {
2524     // add to XCAF
2525     if(!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2526     {
2527       aGDTL = aDGTTool->AddDimension();
2528       Handle(XCAFDoc_Dimension) aDim = XCAFDoc_Dimension::Set(aGDTL);
2529       TCollection_AsciiString aStr("DGT:Dimensional_");
2530       if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2531       {
2532         aStr.AssignCat("Size");
2533       }
2534       else if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
2535       {
2536         aStr.AssignCat("Location");
2537       }
2538       TDataStd_Name::Set(aGDTL, aStr);
2539
2540       if(!aShLS2.IsEmpty())
2541       {
2542         aDGTTool->SetDimension(aShLS1, aShLS2, aGDTL);
2543       }
2544       else
2545       {
2546         TDF_LabelSequence aEmptySeq;
2547         aDGTTool->SetDimension(aShLS1, aEmptySeq, aGDTL);
2548       }
2549     }
2550     else
2551     {
2552       aGDTL = aDGTTool->AddGeomTolerance();
2553       Handle(XCAFDoc_GeomTolerance) aGTol = XCAFDoc_GeomTolerance::Set(aGDTL);
2554       TCollection_AsciiString aStr("DGT:GeomTolerance");
2555       TDataStd_Name::Set(aGDTL, aStr);
2556       aDGTTool->SetGeomTolerance(aShLS1, aGDTL);
2557       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aGTol->GetObject();
2558       if(isAllAround)
2559         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Around);
2560       else if(isAllOver)
2561         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Over);
2562       aGTol->SetObject(anObj);
2563     }
2564     readDatumsAP242(theEnt, aGDTL, theDoc, theWS);
2565   }
2566   return aGDTL;
2567 }
2568
2569 //=======================================================================
2570 //function : setDimObjectToXCAF
2571 //purpose  : 
2572 //=======================================================================
2573 static void setDimObjectToXCAF(const Handle(Standard_Transient)& theEnt,
2574                                            const TDF_Label& aDimL,
2575                                            const Handle(TDocStd_Document)& theDoc,
2576                                            const Handle(XSControl_WorkSession)& theWS)
2577 {
2578   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2579   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2580   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2581   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2582   const Interface_Graph& aGraph = aTP->Graph();
2583   Handle(XCAFDimTolObjects_DimensionObject) aDimObj;
2584   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2585     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) 
2586     return;
2587
2588   Handle(StepShape_DimensionalSize) aDimSize = 
2589     Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2590   Handle(StepShape_DimensionalLocation) aDimLocation = 
2591     Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
2592
2593   Standard_Real aDim1=-1.,aDim2=-1.,aDim3=-1.;
2594   Handle(StepShape_TypeQualifier) aTQ;
2595   Handle(StepShape_ValueFormatTypeQualifier) aVFTQ;
2596   Handle(StepShape_ToleranceValue) aTV;
2597   Handle(StepShape_LimitsAndFits) aLAF;
2598   Handle(StepRepr_CompoundRepresentationItem) aCRI;
2599   Handle(StepGeom_Axis2Placement3d) anAP;
2600
2601   Interface_EntityIterator anIterDim;
2602   if(!aDimSize.IsNull())
2603   {
2604     anIterDim = aGraph.Sharings(aDimSize);
2605   }
2606   else
2607   {
2608     anIterDim = aGraph.Sharings(aDimLocation);
2609   }
2610   for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) {
2611     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR = 
2612       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anIterDim.Value());
2613     Handle(StepShape_PlusMinusTolerance) aPMT = 
2614       Handle(StepShape_PlusMinusTolerance)::DownCast(anIterDim.Value());
2615     if(!aDCR.IsNull()) {
2616       Handle(StepShape_ShapeDimensionRepresentation) aSDR = aDCR->Representation();
2617       if(!aSDR.IsNull()) {
2618         Handle(StepRepr_HArray1OfRepresentationItem) aHARI = aSDR->Items();
2619
2620         if(!aHARI.IsNull())
2621         {
2622           for(Standard_Integer nr = aHARI->Lower(); nr <= aHARI->Upper(); nr++)
2623           {
2624             Handle(StepRepr_RepresentationItem) aDRI =
2625               Handle(StepRepr_RepresentationItem)::DownCast(aHARI->Value(nr));
2626             if(aDRI.IsNull()) continue;
2627
2628             if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2629               //get values
2630               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aRILMWU =
2631                 Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aDRI);
2632               Standard_Real aVal = aRILMWU->GetMeasureWithUnit()->ValueComponent();
2633               StepBasic_Unit anUnit = aRILMWU->GetMeasureWithUnit()->UnitComponent();
2634               Standard_Real aFact=1.;
2635               if(anUnit.IsNull()) continue;
2636               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2637               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2638               if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2639               if(aDim2 > 0)
2640               {
2641                 if(aDim1 > aDim2)
2642                 {
2643                   Standard_Real aTmp = aDim1;
2644                   aDim1 = aDim2;
2645                   aDim2 = aTmp;
2646                 }
2647                 if(aVal < aDim1)
2648                   aDim1 = aVal;
2649                 else if(aVal > aDim2)
2650                   aDim2 = aVal;
2651               }
2652               else if(aDim1 > 0)
2653               {
2654                 if (aVal > aDim1)
2655                   aDim2 = aVal;
2656                 else
2657                 {
2658                   aDim2 = aDim1;
2659                   aDim1 = aVal;
2660                 }
2661               }
2662               else
2663                 aDim1 = aVal;
2664             }
2665             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit))) {
2666               //get values
2667               Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit) aRIPAMWU =
2668                 Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit)::DownCast(aDRI);
2669               Standard_Real aVal = aRIPAMWU->GetMeasureWithUnit()->ValueComponent();
2670               StepBasic_Unit anUnit = aRIPAMWU->GetMeasureWithUnit()->UnitComponent();
2671               Standard_Real aFact=1.;
2672               if(anUnit.IsNull()) continue;
2673               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2674               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2675               if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
2676               if(aDim2 > 0)
2677               {
2678                 if(aDim1 > aDim2)
2679                 {
2680                   Standard_Real aTmp = aDim1;
2681                   aDim1 = aDim2;
2682                   aDim2 = aTmp;
2683                 }
2684                 if(aVal < aDim1)
2685                   aDim1 = aVal;
2686                 else if(aVal > aDim2)
2687                   aDim2 = aVal;
2688               }
2689               else if(aDim1 > 0)
2690               {
2691                 if (aVal > aDim1)
2692                   aDim2 = aVal;
2693                 else
2694                 {
2695                   aDim2 = aDim1;
2696                   aDim1 = aVal;
2697                 }
2698               }
2699               else
2700                 aDim1 = aVal;
2701             }
2702             else if(aDRI->IsKind(STANDARD_TYPE(StepShape_QualifiedRepresentationItem))) {
2703               //get qualifier
2704               Handle(StepShape_QualifiedRepresentationItem) aQRI =
2705                 Handle(StepShape_QualifiedRepresentationItem)::DownCast(aDRI);
2706               for(Standard_Integer l = 1; l <= aQRI->NbQualifiers(); l++)
2707               {
2708                 aTQ = aQRI->Qualifiers()->Value(l).TypeQualifier();
2709                 aVFTQ = aQRI->Qualifiers()->Value(l).ValueFormatTypeQualifier();
2710               }
2711             }
2712             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_CompoundRepresentationItem))) {
2713               aCRI = Handle(StepRepr_CompoundRepresentationItem)::DownCast(aDRI);
2714             }
2715             else if(aDRI->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2716             {
2717               anAP = Handle(StepGeom_Axis2Placement3d)::DownCast(aDRI);
2718             }
2719           }
2720         }
2721       }
2722     }
2723     else if (!aPMT.IsNull())
2724     {
2725       StepShape_ToleranceMethodDefinition aTMD = aPMT->Range();
2726       if(aPMT.IsNull()) continue;
2727       if(aTMD.CaseNumber() == 1)
2728         //! 1 -> ToleranceValue from StepShape
2729         //! 2 -> LimitsAndFits from StepShape
2730       {
2731         //plus minus tolerance 
2732         aTV = aTMD.ToleranceValue();
2733         if (aTV.IsNull()) continue;
2734
2735         Standard_Real aVal = aTV->UpperBound()->ValueComponent();
2736         StepBasic_Unit anUnit = aTV->UpperBound()->UnitComponent();
2737         Standard_Real aFact=1.;
2738         if(anUnit.IsNull()) continue;
2739         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2740         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2741         if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2742         aDim3 = aVal;
2743
2744         aVal = aTV->LowerBound()->ValueComponent();
2745         anUnit = aTV->LowerBound()->UnitComponent();
2746         aFact=1.;
2747         if(anUnit.IsNull()) continue;
2748         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2749         NU = anUnit.NamedUnit();
2750         if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2751         aDim2 = Abs(aVal);
2752       }
2753       else
2754       {
2755         // calss of tolerance
2756         aLAF = aTMD.LimitsAndFits();
2757       }
2758     }
2759   }
2760
2761   if(aDim1<0) return;
2762
2763   aDimObj = new XCAFDimTolObjects_DimensionObject();
2764   if(aDim2 < 0)
2765     aDimObj->SetValue(aDim1);
2766   else if (aDim3 < 0)
2767   {
2768     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1,2);
2769     anArr->SetValue(1,aDim1);
2770     anArr->SetValue(2,aDim2);
2771     aDimObj->SetValues(anArr);
2772   }
2773   else
2774   {
2775     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1,3);
2776     anArr->SetValue(1,aDim1);
2777     anArr->SetValue(2,aDim2);
2778     anArr->SetValue(3,aDim3);
2779     aDimObj->SetValues(anArr);
2780   }
2781   if(!aTQ.IsNull()) 
2782   {
2783     XCAFDimTolObjects_DimensionQualifier aQ;
2784     if (STEPConstruct_GDTProperty::GetDimQualifierType(aTQ->Name(), aQ))
2785     {
2786         aDimObj->SetQualifier(aQ);
2787     }
2788   }
2789
2790   if (!aVFTQ.IsNull())
2791   {
2792     //A typical value would be \91NR2 2.2\92
2793     TCollection_HAsciiString aFormat = aVFTQ->FormatType();
2794     Standard_Integer i = aFormat.Location(1,' ',1,aFormat.Length());
2795     aFormat.SubString(i+1,i+1)->IntegerValue();
2796     aDimObj->SetNbOfDecimalPlaces(aFormat.SubString(i+1,i+1)->IntegerValue(),
2797       aFormat.SubString(i+3,i+3)->IntegerValue());
2798   }
2799
2800   if (!aLAF.IsNull())
2801   { 
2802     //get class of tolerance
2803     Standard_Boolean aHolle = Standard_False;
2804     XCAFDimTolObjects_DimensionFormVariance aFV = XCAFDimTolObjects_DimensionFormVariance_None;
2805     XCAFDimTolObjects_DimensionGrade aG = XCAFDimTolObjects_DimensionGrade_IT01;
2806     STEPConstruct_GDTProperty::GetDimClassOfTolerance(aLAF, aHolle, aFV, aG);
2807     aDimObj->SetClassOfTolerance(aHolle, aFV, aG);
2808   }
2809
2810   if (!aCRI.IsNull() && aCRI->ItemElement()->Length() > 0)
2811   {
2812     //get modifiers
2813     XCAFDimTolObjects_DimensionModifiersSequence aModifiers;
2814     STEPConstruct_GDTProperty::GetDimModifiers(aCRI, aModifiers);
2815     if(aModifiers.Length() > 0)
2816       aDimObj->SetModifiers(aModifiers);
2817   }
2818
2819   Handle(TCollection_HAsciiString) aName;
2820   if(!aDimSize.IsNull())
2821   {
2822     aName = aDimSize->Name();
2823   }
2824   else
2825   {
2826     aName = aDimLocation->Name();
2827   }
2828   XCAFDimTolObjects_DimensionType aType = XCAFDimTolObjects_DimensionType_Location_None;
2829   if (!STEPConstruct_GDTProperty::GetDimType(aName, aType))
2830   {
2831     if(!aDimSize.IsNull())
2832     {
2833       Handle(StepShape_AngularSize) anAngSize= 
2834         Handle(StepShape_AngularSize)::DownCast(aDimSize);
2835       if(!anAngSize.IsNull())
2836       {
2837         //get qualifier for angular value
2838         aType = XCAFDimTolObjects_DimensionType_Size_Angular;
2839         if(anAngSize->AngleSelection() == StepShape_Equal)
2840           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
2841         else if (anAngSize->AngleSelection() == StepShape_Large)
2842           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
2843         else if (anAngSize->AngleSelection() == StepShape_Small)
2844           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
2845       }
2846     }
2847     else
2848     {
2849       Handle(StepShape_AngularLocation) anAngLoc= 
2850         Handle(StepShape_AngularLocation)::DownCast(aDimLocation);
2851       if(!anAngLoc.IsNull())
2852       {
2853         //get qualifier for angular value
2854         aType = XCAFDimTolObjects_DimensionType_Location_Angular;
2855         if(anAngLoc->AngleSelection() == StepShape_Equal)
2856           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
2857         else if (anAngLoc->AngleSelection() == StepShape_Large)
2858           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
2859         else if (anAngLoc->AngleSelection() == StepShape_Small)
2860           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
2861       }
2862     }
2863     if(aType == XCAFDimTolObjects_DimensionType_Location_None)
2864     {
2865       Handle(StepRepr_ShapeAspect) aPSA;
2866       if(!aDimSize.IsNull())
2867       {
2868         Handle(StepShape_DimensionalSizeWithPath) aDimSizeWithPath= 
2869           Handle(StepShape_DimensionalSizeWithPath)::DownCast(aDimSize);
2870         if (!aDimSizeWithPath.IsNull())
2871         {
2872           aType = XCAFDimTolObjects_DimensionType_Size_WithPath;
2873           aPSA = aDimSizeWithPath->Path();
2874         }
2875       }
2876       else
2877       {
2878         Handle(StepShape_DimensionalLocationWithPath) aDimLocWithPath= 
2879           Handle(StepShape_DimensionalLocationWithPath)::DownCast(aDimLocation);
2880         if (!aDimLocWithPath.IsNull())
2881         {
2882           aType = XCAFDimTolObjects_DimensionType_Location_WithPath;
2883           aPSA = aDimLocWithPath->Path();
2884         }
2885       }
2886
2887       if(!aPSA.IsNull())
2888       {
2889         //for DimensionalLocationWithPath
2890         Handle(StepGeom_GeometricRepresentationItem) aGRI;
2891         Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
2892         Interface_EntityIterator anIterDSWP = aGraph.Sharings(aPSA);
2893         for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
2894           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2895         }
2896         if(aPGISU.IsNull()) return;
2897         if(aPGISU->NbIdentifiedItem() > 0) {
2898           aGRI = Handle(StepGeom_GeometricRepresentationItem)::DownCast(aPGISU->IdentifiedItemValue(1));
2899         }
2900         if(aGRI.IsNull()) return;
2901         Handle(StepRepr_RepresentationItem) aPRI;
2902         Interface_EntityIterator anIterGRI = aGraph.Sharings(aGRI);
2903         for(anIterGRI.Start(); anIterGRI.More() && aPGISU.IsNull(); anIterGRI.Next()) {
2904           aPRI = Handle(StepRepr_RepresentationItem)::DownCast(anIterGRI.Value());
2905         }
2906         Standard_Integer anIndex = aTP->MapIndex(aPRI);
2907         TopoDS_Edge aSh;
2908         if(anIndex >0) {
2909           Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2910           aSh = TopoDS::Edge(TransferBRep::ShapeResult(aBinder));
2911         }
2912         if(aSh.IsNull()) return; 
2913         aDimObj->SetPath(aSh);
2914       }
2915       else if(!anAP.IsNull())
2916       {
2917         if(anAP->Name()->String().IsEqual("orientation") && !anAP->Axis().IsNull())
2918         {
2919           //for Oriented Dimensional Location
2920           Handle(TColStd_HArray1OfReal) aDirArr = anAP->RefDirection()->DirectionRatios();
2921           gp_Dir aDir;
2922           if(!aDirArr.IsNull() && aDirArr->Length() > 2)
2923           {
2924             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2925             aDimObj->SetDirection(aDir);
2926           }
2927           else if(aDirArr->Length() > 1)
2928           {
2929             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, 0);
2930             aDimObj->SetDirection(aDir);
2931           }
2932         }
2933       }
2934     }
2935   }
2936   aDimObj->SetType(aType);
2937
2938   if(!aDimObj.IsNull())
2939   {
2940     Handle(XCAFDoc_Dimension) aDim;
2941     if(aDimL.FindAttribute(XCAFDoc_Dimension::GetID(),aDim))
2942     {
2943       aDim->SetObject(aDimObj);
2944     }
2945   }
2946 }
2947
2948 //=======================================================================
2949 //function : getTolType
2950 //purpose  : 
2951 //=======================================================================
2952 static Standard_Boolean getTolType(const Handle(Standard_Transient)& theEnt,
2953                        XCAFDimTolObjects_GeomToleranceType& theType)
2954 {
2955   if(!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) 
2956     return Standard_False;
2957   theType = XCAFDimTolObjects_GeomToleranceType_None;
2958   if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRef)))
2959   {
2960     Handle(StepDimTol_GeoTolAndGeoTolWthDatRef) anE = Handle(StepDimTol_GeoTolAndGeoTolWthDatRef)::DownCast(theEnt);
2961     theType = (XCAFDimTolObjects_GeomToleranceType)anE->GetToleranceType();
2962   }
2963   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))
2964   {
2965     theType = XCAFDimTolObjects_GeomToleranceType_Angularity;
2966   }
2967   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))
2968   {
2969     theType = XCAFDimTolObjects_GeomToleranceType_CircularRunout;
2970   }
2971   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance)))
2972   {
2973     theType = XCAFDimTolObjects_GeomToleranceType_CircularityOrRoundness;
2974   }
2975   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))
2976   {
2977     theType = XCAFDimTolObjects_GeomToleranceType_Coaxiality;
2978   }
2979   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))
2980   {
2981     theType = XCAFDimTolObjects_GeomToleranceType_Concentricity;
2982   }
2983   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance)))
2984   {
2985     theType = XCAFDimTolObjects_GeomToleranceType_Cylindricity;
2986   }
2987   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance)))
2988   {
2989     theType = XCAFDimTolObjects_GeomToleranceType_Flatness;
2990   }
2991   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))
2992   {
2993     theType = XCAFDimTolObjects_GeomToleranceType_Parallelism;
2994   }
2995   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance)))
2996   {
2997     theType = XCAFDimTolObjects_GeomToleranceType_Perpendicularity;
2998   }
2999   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance)) || 
3000      theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)))
3001   {
3002     theType = XCAFDimTolObjects_GeomToleranceType_Position;
3003   }
3004   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance)))
3005   {
3006     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfLine;
3007   }
3008   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance)))
3009   {
3010     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfSurface;
3011   }
3012   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance)))
3013   {
3014     theType = XCAFDimTolObjects_GeomToleranceType_Straightness;
3015   }
3016   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))
3017   {
3018     theType = XCAFDimTolObjects_GeomToleranceType_Symmetry;
3019   }
3020   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))
3021   {
3022     theType = XCAFDimTolObjects_GeomToleranceType_TotalRunout;
3023   }
3024   return Standard_True;
3025 }
3026 //=======================================================================
3027 //function : setGeomTolObjectToXCAF
3028 //purpose  : 
3029 //=======================================================================
3030 static void setGeomTolObjectToXCAF(const Handle(Standard_Transient)& theEnt,
3031                                            const TDF_Label& theTolL,
3032                                            const Handle(TDocStd_Document)& theDoc,
3033                                            const Handle(XSControl_WorkSession)& theWS)
3034 {
3035   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
3036   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
3037   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
3038   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
3039   const Interface_Graph& aGraph = aTP->Graph();
3040   Handle(XCAFDoc_GeomTolerance) aGTol;
3041   if(!theTolL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aGTol))
3042   {
3043     return;
3044   }
3045   Handle(XCAFDimTolObjects_GeomToleranceObject) aTolObj = aGTol->GetObject();
3046   Handle(StepDimTol_GeometricTolerance) aTolEnt = Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
3047
3048   XCAFDimTolObjects_GeomToleranceType aType = XCAFDimTolObjects_GeomToleranceType_None;
3049   getTolType(theEnt, aType);
3050   aTolObj->SetType(aType);
3051   if(!aTolEnt->Magnitude().IsNull()){
3052     //get value
3053     Standard_Real aVal = aTolEnt->Magnitude()->ValueComponent();
3054     StepBasic_Unit anUnit = aTolEnt->Magnitude()->UnitComponent();
3055     Standard_Real aFact=1.;
3056     if(anUnit.IsNull()) return;
3057     if( !(anUnit.CaseNum(anUnit.Value())==1) ) return;
3058     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3059     if(GetLengthConversionFactor(NU,aFact))
3060       aVal=aVal*aFact;
3061     aTolObj->SetValue(aVal);
3062   }
3063   //get modifiers
3064   XCAFDimTolObjects_GeomToleranceTypeValue aTypeV = XCAFDimTolObjects_GeomToleranceTypeValue_None;
3065   Interface_EntityIterator anIter = aGraph.Sharings(aTolEnt);
3066   for(anIter.Start(); anIter.More(); anIter.Next()) {
3067     if(anIter.Value()->IsKind(STANDARD_TYPE(StepDimTol_ToleranceZone))){
3068       Handle(StepDimTol_ToleranceZoneForm) aForm 
3069                             = Handle(StepDimTol_ToleranceZone)::DownCast(anIter.Value())->Form();
3070       STEPConstruct_GDTProperty::GetTolValueType(aForm->Name(), aTypeV);
3071       Interface_EntityIterator anIt = aGraph.Sharings(anIter.Value());
3072       for(anIt.Start(); anIt.More(); anIt.Next()) {
3073         if(anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_ProjectedZoneDefinition))){
3074           Handle(StepDimTol_ProjectedZoneDefinition) aPZone
3075                               = Handle(StepDimTol_ProjectedZoneDefinition)::DownCast(anIt.Value());
3076           if(!aPZone->ProjectionLength().IsNull())
3077           {
3078             Standard_Real aVal = aPZone->ProjectionLength()->ValueComponent();
3079             StepBasic_Unit anUnit = aPZone->ProjectionLength()->UnitComponent();
3080             Standard_Real aFact=1.;
3081             if(anUnit.IsNull()) return;
3082             if( !(anUnit.CaseNum(anUnit.Value())==1) ) return;
3083             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3084             if(GetLengthConversionFactor(NU,aFact))
3085               aVal=aVal*aFact;
3086             aTolObj->SetValueOfZoneModifier(aVal);
3087           }
3088         }
3089         else if (anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_RunoutZoneDefinition)))
3090         {
3091           Handle(StepDimTol_RunoutZoneDefinition) aRZone
3092                                 = Handle(StepDimTol_RunoutZoneDefinition)::DownCast(anIt.Value());
3093           if(!aRZone->Orientation().IsNull())
3094           {
3095             Standard_Real aVal = aRZone->Orientation()->Angle()->ValueComponent();
3096             StepBasic_Unit anUnit = aRZone->Orientation()->Angle()->UnitComponent();
3097             Standard_Real aFact=1.;
3098             if(anUnit.IsNull()) continue;
3099             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3100             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3101             if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
3102             aTolObj->SetValueOfZoneModifier(aVal);
3103           }
3104         }
3105       }
3106       aTolObj->SetTypeOfValue(aTypeV);
3107     }
3108   }
3109   Handle(StepDimTol_HArray1OfGeometricToleranceModifier) aModifiers;
3110   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithModifiers)))
3111   {
3112     aModifiers = Handle(StepDimTol_GeometricToleranceWithModifiers)::DownCast(aTolEnt)->Modifiers();
3113   }
3114   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)))
3115   {
3116     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)
3117                             ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3118   }
3119   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMod)))
3120   {
3121     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthMod)
3122                              ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3123   }
3124   if(!aModifiers.IsNull())
3125   {
3126     for(Standard_Integer i = aModifiers->Lower(); i <= aModifiers->Upper(); i++)
3127     {
3128       if(aModifiers->Value(i) == StepDimTol_GTMLeastMaterialRequirement)
3129         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_L);
3130       else if (aModifiers->Value(i) == StepDimTol_GTMMaximumMaterialRequirement)
3131         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_M);
3132       else
3133         aTolObj->AddModifier((XCAFDimTolObjects_GeomToleranceModif)aModifiers->Value(i));
3134     }
3135   }
3136   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithMaximumTolerance)))
3137   {
3138     Handle(StepDimTol_GeometricToleranceWithMaximumTolerance) aMax = Handle(StepDimTol_GeometricToleranceWithMaximumTolerance)::DownCast(aTolEnt);
3139     Standard_Real aVal = aMax->MaximumUpperTolerance()->ValueComponent();
3140     StepBasic_Unit anUnit = aMax->MaximumUpperTolerance()->UnitComponent();
3141     Standard_Real aFact=1.;
3142     if(anUnit.IsNull()) return;
3143     if( !(anUnit.CaseNum(anUnit.Value())==1) ) return;
3144     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3145     if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
3146     aTolObj->SetMaxValueModifier(aVal);
3147   }
3148
3149   aGTol->SetObject(aTolObj);
3150 }
3151
3152 //=======================================================================
3153 //function : ReadGDTs
3154 //purpose  : 
3155 //=======================================================================
3156
3157 Standard_Boolean STEPCAFControl_Reader::ReadGDTs(const Handle(XSControl_WorkSession)& theWS,
3158                                                  Handle(TDocStd_Document)& theDoc) const
3159 {
3160   Handle(Interface_InterfaceModel) aModel = theWS->Model();
3161   Handle(StepData_StepModel) aSM = Handle(StepData_StepModel)::DownCast(aModel);
3162   Interface_EntityIterator anI = aSM->Header();
3163   Handle(HeaderSection_FileSchema) aH;
3164   for(anI.Start(); anI.More() && aH.IsNull();anI.Next())
3165     aH = Handle(HeaderSection_FileSchema)::DownCast(anI.Value());
3166   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
3167   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
3168   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
3169   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
3170   if ( aDGTTool.IsNull() ) return Standard_False;
3171
3172   Standard_Integer nb = aModel->NbEntities();
3173   for(Standard_Integer i=1; i<=nb; i++) {
3174     Handle(Standard_Transient) anEnt = aModel->Value(i);
3175     if(anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) || 
3176        anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
3177        anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3178       TDF_Label aGDTL = createGDTObjectInXCAF(anEnt,theDoc,theWS);
3179       if(!aGDTL.IsNull()){
3180         if(anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))){
3181           setGeomTolObjectToXCAF(anEnt, aGDTL,theDoc,theWS);
3182         }
3183         else {
3184           setDimObjectToXCAF(anEnt, aGDTL,theDoc,theWS);
3185         }
3186       }
3187     }
3188   }
3189   return Standard_True;
3190 }
3191
3192
3193 //=======================================================================
3194 //function : FindSolidForPDS
3195 //purpose  : auxilary
3196 //=======================================================================
3197
3198 static Handle(StepShape_SolidModel) FindSolidForPDS(const Handle(StepRepr_ProductDefinitionShape) &PDS,
3199                                                     const Interface_Graph &graph)
3200 {
3201   Handle(StepShape_SolidModel) SM;
3202   Interface_EntityIterator subs = graph.Sharings(PDS);
3203   Handle(StepShape_ShapeRepresentation) SR;
3204   for(subs.Start(); subs.More() && SM.IsNull(); subs.Next()) {
3205     Handle(StepShape_ShapeDefinitionRepresentation) SDR =
3206       Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
3207     if(SDR.IsNull()) continue;
3208     SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
3209     if(SR.IsNull()) continue;
3210     for(Standard_Integer i=1; i<=SR->NbItems() && SM.IsNull(); i++) {
3211       SM = Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(i));
3212     }
3213     if(SM.IsNull()) {
3214       Interface_EntityIterator subs1 = graph.Sharings(SR);
3215       for(subs1.Start(); subs1.More() && SM.IsNull(); subs1.Next()) {
3216         Handle(StepRepr_RepresentationRelationship) RR =
3217           Handle(StepRepr_RepresentationRelationship)::DownCast(subs1.Value());
3218         if(RR.IsNull()) continue;
3219         Handle(StepShape_ShapeRepresentation) SR2;
3220         if(RR->Rep1()==SR) SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep2());
3221         else SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep1());
3222         if(SR2.IsNull()) continue;
3223         for(Standard_Integer i2=1; i2<=SR2->NbItems() && SM.IsNull(); i2++) {
3224           SM = Handle(StepShape_SolidModel)::DownCast(SR2->ItemsValue(i2));
3225         }
3226       }
3227     }
3228   }
3229   return SM;
3230 }
3231
3232
3233 //=======================================================================
3234 //function : ReadMaterials
3235 //purpose  : 
3236 //=======================================================================
3237
3238 Standard_Boolean STEPCAFControl_Reader::ReadMaterials(const Handle(XSControl_WorkSession) &WS,
3239                                                       Handle(TDocStd_Document)& Doc,
3240                                                       const Handle(TColStd_HSequenceOfTransient) &SeqPDS) const
3241 {
3242   Handle(Interface_InterfaceModel) Model = WS->Model();
3243   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
3244   Handle(XSControl_TransferReader) TR = WS->TransferReader();
3245   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
3246   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( Doc->Main() );
3247   if(MatTool.IsNull()) return Standard_False;
3248   
3249   const Interface_Graph& graph = TP->Graph();
3250   for(Standard_Integer i=1; i<=SeqPDS->Length(); i++) {
3251     Handle(StepRepr_ProductDefinitionShape) PDS =
3252       Handle(StepRepr_ProductDefinitionShape)::DownCast(SeqPDS->Value(i));
3253     if(PDS.IsNull()) 
3254       continue;
3255     Handle(StepBasic_ProductDefinition) aProdDef = PDS->Definition().ProductDefinition();
3256     if(aProdDef.IsNull())
3257       continue;
3258     Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString("");
3259     Handle(TCollection_HAsciiString) aDescription = new TCollection_HAsciiString("");
3260     Handle(TCollection_HAsciiString) aDensName = new TCollection_HAsciiString("");
3261     Handle(TCollection_HAsciiString) aDensValType = new TCollection_HAsciiString("");
3262     Standard_Real aDensity=0;
3263     Interface_EntityIterator subs = graph.Sharings( aProdDef);
3264     for(subs.Start(); subs.More(); subs.Next()) {
3265       Handle(StepRepr_PropertyDefinition) PropD =
3266         Handle(StepRepr_PropertyDefinition)::DownCast(subs.Value());
3267       if(PropD.IsNull()) continue;
3268       Interface_EntityIterator subs1 = graph.Sharings(PropD);
3269       for(subs1.Start(); subs1.More(); subs1.Next()) {
3270         Handle(StepRepr_PropertyDefinitionRepresentation) PDR =
3271           Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast(subs1.Value());
3272         if(PDR.IsNull()) continue;
3273         Handle(StepRepr_Representation) Repr = PDR->UsedRepresentation();
3274         if(Repr.IsNull()) continue;
3275         Standard_Integer ir;
3276         for(ir=1; ir<=Repr->NbItems(); ir++) {
3277           Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(ir);
3278           if(RI.IsNull()) continue;
3279           if(RI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
3280             // find name and description for material
3281             Handle(StepRepr_DescriptiveRepresentationItem) DRI =
3282               Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(RI);
3283             aName = DRI->Name();
3284             
3285             aDescription = DRI->Description();
3286             if(aName.IsNull())
3287               aName = aDescription;
3288           }
3289           if(RI->IsKind(STANDARD_TYPE(StepRepr_MeasureRepresentationItem))) {
3290             // try to find density for material
3291             Handle(StepRepr_MeasureRepresentationItem) MRI =
3292               Handle(StepRepr_MeasureRepresentationItem)::DownCast(RI);
3293             aDensity = MRI->Measure()->ValueComponent();
3294             aDensName = MRI->Name();
3295             aDensValType = new TCollection_HAsciiString(MRI->Measure()->ValueComponentMember()->Name());
3296             StepBasic_Unit aUnit = MRI->Measure()->UnitComponent();
3297             if(!aUnit.IsNull()) {
3298               Handle(StepBasic_DerivedUnit) DU = aUnit.DerivedUnit();
3299               if(DU.IsNull()) continue;
3300               for(Standard_Integer idu=1; idu<=DU->NbElements(); idu++) {
3301                 Handle(StepBasic_DerivedUnitElement) DUE = DU->ElementsValue(idu);
3302                 Handle(StepBasic_NamedUnit) NU = DUE->Unit();
3303                 Standard_Real afact=1.;
3304                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit))) {
3305                   if(GetLengthConversionFactor(NU,afact)) aDensity = aDensity/(afact*afact*afact);
3306                   // transfer length value for Density from millimeter to santimeter
3307                   // in order to result density has dimension gram/(sm*sm*sm)
3308                   aDensity = aDensity*1000.;
3309                 }
3310                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit))) {
3311                   if(GetMassConversionFactor(NU,afact)) aDensity=aDensity*afact;
3312                 }
3313               }
3314             }
3315           }
3316         }
3317       }
3318     }
3319    
3320     if( aName.IsNull() || aName->Length()==0 ) 
3321       continue;
3322     // find shape label amd create Material link
3323     TopoDS_Shape aSh;
3324     Handle(StepShape_SolidModel) SM = FindSolidForPDS(PDS,graph);
3325     if(!SM.IsNull()) {
3326       Standard_Integer index = TP->MapIndex(SM);
3327       if(index >0) {
3328         Handle(Transfer_Binder) binder = TP->MapItem(index);
3329         if(!binder.IsNull())
3330           aSh = TransferBRep::ShapeResult(binder);
3331       }
3332     }
3333     if(aSh.IsNull()) continue; 
3334     TDF_Label shL;
3335     if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
3336     MatTool->SetMaterial(shL,aName,aDescription,aDensity,aDensName,aDensValType);
3337   }
3338
3339   return Standard_True;
3340 }
3341
3342 //=======================================================================
3343 //function : SettleShapeData
3344 //purpose  :
3345 //=======================================================================
3346
3347 TDF_Label STEPCAFControl_Reader::SettleShapeData(const Handle(StepRepr_RepresentationItem)& theItem,
3348                                                  TDF_Label& theLab,
3349                                                  const Handle(XCAFDoc_ShapeTool)& theShapeTool,
3350                                                  const Handle(Transfer_TransientProcess)& TP) const
3351 {
3352   TDF_Label aResult = theLab;
3353
3354   Handle(TCollection_HAsciiString) hName = theItem->Name();
3355   if ( hName.IsNull() || hName->IsEmpty() )
3356     return aResult;
3357
3358   Handle(Transfer_Binder) aBinder = TP->Find(theItem);
3359   if ( aBinder.IsNull() )
3360     return aResult;
3361
3362   TopoDS_Shape aShape = TransferBRep::ShapeResult(aBinder);
3363   if ( aShape.IsNull() )
3364     return aResult;
3365
3366   // Allocate sub-Label
3367   aResult = AllocateSubLabel(theLab);
3368
3369   TCollection_AsciiString aName = hName->String();
3370   TDataStd_Name::Set(aResult, aName);
3371   theShapeTool->SetShape(aResult, aShape);
3372
3373   return aResult;
3374 }
3375
3376 //=======================================================================
3377 //function : ExpandSubShapes
3378 //purpose  :
3379 //=======================================================================
3380
3381 void STEPCAFControl_Reader::ExpandSubShapes(const Handle(XCAFDoc_ShapeTool)& ShapeTool,
3382                                             const XCAFDoc_DataMapOfShapeLabel& ShapeLabelMap,
3383                                             const STEPCAFControl_DataMapOfShapePD& ShapePDMap) const
3384 {
3385   const Handle(Transfer_TransientProcess)& TP = Reader().WS()->TransferReader()->TransientProcess();
3386   NCollection_DataMap<TopoDS_Shape, Handle(TCollection_HAsciiString)> ShapeNameMap;
3387   TColStd_MapOfTransient aRepItems;
3388
3389   // Read translation control variables
3390   Standard_Boolean doReadSNames = (Interface_Static::IVal("read.stepcaf.subshapes.name") > 0);
3391
3392   if ( !doReadSNames )
3393     return;
3394
3395   const Interface_Graph& Graph = Reader().WS()->Graph();
3396
3397   for ( STEPCAFControl_DataMapIteratorOfDataMapOfShapePD it(ShapePDMap); it.More(); it.Next() )
3398   {
3399     const TopoDS_Shape& aRootShape = it.Key();
3400     const Handle(StepBasic_ProductDefinition)& aPDef = it.Value();
3401     if ( aPDef.IsNull() )
3402       continue;
3403
3404     // Find SDR by Product
3405     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
3406     Interface_EntityIterator entIt = Graph.TypedSharings( aPDef, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation) );
3407     for ( entIt.Start(); entIt.More(); entIt.Next() )
3408     {
3409       const Handle(Standard_Transient)& aReferer = entIt.Value();
3410       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(aReferer);
3411       if ( !aSDR.IsNull() )
3412         break;
3413     }
3414
3415     if ( aSDR.IsNull() )
3416       continue;
3417
3418     // Access shape representation
3419     Handle(StepShape_ShapeRepresentation)
3420       aShapeRepr = Handle(StepShape_ShapeRepresentation)::DownCast( aSDR->UsedRepresentation() );
3421
3422     if ( aShapeRepr.IsNull() )
3423       continue;
3424
3425     // Access representation items
3426     Handle(StepRepr_HArray1OfRepresentationItem) aReprItems = aShapeRepr->Items();
3427
3428     if ( aReprItems.IsNull() )
3429       continue;
3430
3431     if ( !ShapeLabelMap.IsBound(aRootShape) )
3432       continue;
3433
3434     TDF_Label aRootLab = ShapeLabelMap.Find(aRootShape);
3435
3436     StepRepr_SequenceOfRepresentationItem aMSBSeq;
3437     StepRepr_SequenceOfRepresentationItem aSBSMSeq;
3438
3439     // Iterate over the top level representation items collecting the
3440     // topological containers to expand
3441     for ( Standard_Integer i = aReprItems->Lower(); i <= aReprItems->Upper(); ++i )
3442     {
3443       Handle(StepRepr_RepresentationItem) aTRepr = aReprItems->Value(i);
3444       if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ManifoldSolidBrep) ) )
3445         aMSBSeq.Append(aTRepr);
3446       else if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ShellBasedSurfaceModel) ) )
3447         aSBSMSeq.Append(aTRepr);
3448     }
3449
3450     // Insert intermediate OCAF Labels for SOLIDs in case there are more
3451     // than one Manifold Solid BRep in the Shape Representation
3452     Standard_Boolean doInsertSolidLab = (aMSBSeq.Length() > 1);
3453
3454     // Expand Manifold Solid BReps
3455     for ( Standard_Integer i = 1; i <= aMSBSeq.Length(); ++i )
3456     {
3457       const Handle(StepRepr_RepresentationItem)& aManiRepr = aMSBSeq.Value(i);
3458
3459       // Put additional Label for SOLID
3460       TDF_Label aManiLab;
3461       if ( doInsertSolidLab )
3462         aManiLab = SettleShapeData(aManiRepr, aRootLab, ShapeTool, TP);
3463       else
3464         aManiLab = aRootLab;
3465
3466       ExpandManifoldSolidBrep(aManiLab, aMSBSeq.Value(i), TP, ShapeTool);
3467     }
3468
3469     // Expand Shell-Based Surface Models
3470     for ( Standard_Integer i = 1; i <= aSBSMSeq.Length(); ++i )
3471       ExpandSBSM(aRootLab, aSBSMSeq.Value(i), TP, ShapeTool);
3472   }
3473 }
3474
3475 //=======================================================================
3476 //function : ExpandManifoldSolidBrep
3477 //purpose  :
3478 //=======================================================================
3479
3480 void STEPCAFControl_Reader::ExpandManifoldSolidBrep(TDF_Label& ShapeLab,
3481                                                     const Handle(StepRepr_RepresentationItem)& Repr,
3482                                                     const Handle(Transfer_TransientProcess)& TP,
3483                                                     const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
3484 {
3485   // Access outer shell
3486   Handle(StepShape_ManifoldSolidBrep) aMSB = Handle(StepShape_ManifoldSolidBrep)::DownCast(Repr);
3487   Handle(StepShape_ConnectedFaceSet) aShell = aMSB->Outer();
3488
3489   // Expand shell contents to CAF tree
3490   ExpandShell(aShell, ShapeLab, TP, ShapeTool);
3491 }
3492
3493 //=======================================================================
3494 //function : ExpandSBSM
3495 //purpose  :
3496 //=======================================================================
3497
3498 void STEPCAFControl_Reader::ExpandSBSM(TDF_Label& ShapeLab,
3499                                        const Handle(StepRepr_RepresentationItem)& Repr,
3500                                        const Handle(Transfer_TransientProcess)& TP,
3501                                        const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
3502 {
3503   Handle(StepShape_ShellBasedSurfaceModel) aSBSM = Handle(StepShape_ShellBasedSurfaceModel)::DownCast(Repr);
3504
3505   // Access boundary shells
3506   Handle(StepShape_HArray1OfShell) aShells = aSBSM->SbsmBoundary();
3507   for ( Standard_Integer s = aShells->Lower(); s <= aShells->Upper(); ++s )
3508   {
3509     const StepShape_Shell& aShell = aShells->Value(s);
3510     Handle(StepShape_ConnectedFaceSet) aCFS;
3511     Handle(StepShape_OpenShell) anOpenShell = aShell.OpenShell();
3512     Handle(StepShape_ClosedShell) aClosedShell = aShell.ClosedShell();
3513
3514     if ( !anOpenShell.IsNull() )
3515       aCFS = anOpenShell;
3516     else
3517       aCFS = aClosedShell;
3518
3519     ExpandShell(aCFS, ShapeLab, TP, ShapeTool);
3520   }
3521 }
3522
3523 //=======================================================================
3524 //function : ExpandShell
3525 //purpose  :
3526 //=======================================================================
3527
3528 void STEPCAFControl_Reader::ExpandShell(const Handle(StepShape_ConnectedFaceSet)& Shell,
3529                                         TDF_Label& RootLab,
3530                                         const Handle(Transfer_TransientProcess)& TP,
3531                                         const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
3532 {
3533   // Record CAF data
3534   TDF_Label aShellLab = SettleShapeData(Shell, RootLab, ShapeTool, TP);
3535
3536   // Access faces
3537   Handle(StepShape_HArray1OfFace) aFaces = Shell->CfsFaces();
3538   for ( Standard_Integer f = aFaces->Lower(); f <= aFaces->Upper(); ++f )
3539   {
3540     const Handle(StepShape_Face)& aFace = aFaces->Value(f);
3541
3542     // Record CAF data
3543     TDF_Label aFaceLab = SettleShapeData(aFace, aShellLab, ShapeTool, TP);
3544
3545     // Access face bounds
3546     Handle(StepShape_HArray1OfFaceBound) aWires = aFace->Bounds();
3547     for ( Standard_Integer w = aWires->Lower(); w <= aWires->Upper(); ++w )
3548     {
3549       const Handle(StepShape_Loop)& aWire = aWires->Value(w)->Bound();
3550
3551       // Record CAF data
3552       TDF_Label aWireLab = SettleShapeData(aWire, aFaceLab, ShapeTool, TP);
3553
3554       // Access wire edges
3555       // Currently only EDGE LOOPs are considered (!)
3556       if ( !aWire->IsInstance( STANDARD_TYPE(StepShape_EdgeLoop) ) )
3557         continue;
3558
3559       // Access edges
3560       Handle(StepShape_EdgeLoop) anEdgeLoop = Handle(StepShape_EdgeLoop)::DownCast(aWire);
3561       Handle(StepShape_HArray1OfOrientedEdge) anEdges = anEdgeLoop->EdgeList();
3562       for ( Standard_Integer e = anEdges->Lower(); e <= anEdges->Upper(); ++e )
3563       {
3564         Handle(StepShape_Edge) anEdge = anEdges->Value(e)->EdgeElement();
3565
3566         // Record CAF data
3567         TDF_Label anEdgeLab = SettleShapeData(anEdge, aWireLab, ShapeTool, TP);
3568
3569         // Access vertices
3570         Handle(StepShape_Vertex) aV1 = anEdge->EdgeStart();
3571         Handle(StepShape_Vertex) aV2 = anEdge->EdgeEnd();
3572
3573         // Record CAF data
3574         SettleShapeData(aV1, anEdgeLab, ShapeTool, TP);
3575         SettleShapeData(aV2, anEdgeLab, ShapeTool, TP);
3576       }
3577     }
3578   }
3579 }
3580
3581 //=======================================================================
3582 //function : SetColorMode
3583 //purpose  : 
3584 //=======================================================================
3585
3586 void STEPCAFControl_Reader::SetColorMode (const Standard_Boolean colormode)
3587 {
3588   myColorMode = colormode;
3589 }
3590
3591 //=======================================================================
3592 //function : GetColorMode
3593 //purpose  : 
3594 //=======================================================================
3595
3596 Standard_Boolean STEPCAFControl_Reader::GetColorMode () const
3597 {
3598   return myColorMode;
3599 }
3600
3601 //=======================================================================
3602 //function : SetNameMode
3603 //purpose  : 
3604 //=======================================================================
3605
3606 void STEPCAFControl_Reader::SetNameMode (const Standard_Boolean namemode)
3607 {
3608   myNameMode = namemode;
3609 }
3610
3611 //=======================================================================
3612 //function : GetNameMode
3613 //purpose  : 
3614 //=======================================================================
3615
3616 Standard_Boolean STEPCAFControl_Reader::GetNameMode () const
3617 {
3618   return myNameMode;
3619 }
3620
3621 //=======================================================================
3622 //function : SetLayerMode
3623 //purpose  : 
3624 //=======================================================================
3625
3626 void STEPCAFControl_Reader::SetLayerMode (const Standard_Boolean layermode)
3627 {
3628   myLayerMode = layermode;
3629 }
3630
3631 //=======================================================================
3632 //function : GetLayerMode
3633 //purpose  : 
3634 //=======================================================================
3635
3636 Standard_Boolean STEPCAFControl_Reader::GetLayerMode () const
3637 {
3638   return myLayerMode;
3639 }
3640
3641 //=======================================================================
3642 //function : SetPropsMode
3643 //purpose  : 
3644 //=======================================================================
3645
3646 void STEPCAFControl_Reader::SetPropsMode (const Standard_Boolean propsmode)
3647 {
3648   myPropsMode = propsmode;
3649 }
3650
3651 //=======================================================================
3652 //function : GetPropsMode
3653 //purpose  : 
3654 //=======================================================================
3655
3656 Standard_Boolean STEPCAFControl_Reader::GetPropsMode () const
3657 {
3658   return myPropsMode;
3659 }
3660
3661 //=======================================================================
3662 //function : SetSHUOMode
3663 //purpose  : 
3664 //=======================================================================
3665
3666 void STEPCAFControl_Reader::SetSHUOMode (const Standard_Boolean mode)
3667 {
3668   mySHUOMode = mode;
3669 }
3670
3671 //=======================================================================
3672 //function : GetSHUOMode
3673 //purpose  : 
3674 //=======================================================================
3675
3676 Standard_Boolean STEPCAFControl_Reader::GetSHUOMode () const
3677 {
3678   return mySHUOMode;
3679 }
3680
3681 //=======================================================================
3682 //function : SetGDTMode
3683 //purpose  : 
3684 //=======================================================================
3685
3686 void STEPCAFControl_Reader::SetGDTMode (const Standard_Boolean gdtmode)
3687 {
3688   myGDTMode = gdtmode;
3689 }
3690
3691 //=======================================================================
3692 //function : GetGDTMode
3693 //purpose  : 
3694 //=======================================================================
3695
3696 Standard_Boolean STEPCAFControl_Reader::GetGDTMode () const
3697 {
3698   return myGDTMode;
3699 }
3700
3701
3702 //=======================================================================
3703 //function : SetMatMode
3704 //purpose  : 
3705 //=======================================================================
3706
3707 void STEPCAFControl_Reader::SetMatMode (const Standard_Boolean matmode)
3708 {
3709   myMatMode = matmode;
3710 }
3711
3712 //=======================================================================
3713 //function : GetMatMode
3714 //purpose  : 
3715 //=======================================================================
3716
3717 Standard_Boolean STEPCAFControl_Reader::GetMatMode () const
3718 {
3719   return myMatMode;
3720 }