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