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