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