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