1d6f28e2fec845671de145cac5a86f65eabcd065
[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 #include <STEPCAFControl_Reader.hxx>
17
18 #include <BRep_Builder.hxx>
19 #include <Geom_Axis2Placement.hxx>
20 #include <Geom_CartesianPoint.hxx>
21 #include <Geom_Plane.hxx>
22 #include <Interface_EntityIterator.hxx>
23 #include <Interface_InterfaceModel.hxx>
24 #include <StepData_StepModel.hxx>
25 #include <HeaderSection_FileSchema.hxx>
26 #include <Interface_Static.hxx>
27 #include <Message_ProgressScope.hxx>
28 #include <NCollection_DataMap.hxx>
29 #include <OSD_Path.hxx>
30 #include <Quantity_Color.hxx>
31 #include <Quantity_ColorRGBA.hxx>
32 #include <StepAP214_AppliedExternalIdentificationAssignment.hxx>
33 #include <StepBasic_ConversionBasedUnitAndLengthUnit.hxx>
34 #include <StepBasic_ConversionBasedUnitAndPlaneAngleUnit.hxx>
35 #include <StepBasic_ConversionBasedUnitAndMassUnit.hxx>
36 #include <StepBasic_DerivedUnit.hxx>
37 #include <StepBasic_DerivedUnitElement.hxx>
38 #include <StepBasic_MeasureValueMember.hxx>
39 #include <StepBasic_MeasureWithUnit.hxx>
40 #include <StepBasic_NamedUnit.hxx>
41 #include <StepBasic_Product.hxx>
42 #include <StepBasic_ProductDefinition.hxx>
43 #include <StepBasic_ProductDefinitionFormation.hxx>
44 #include <StepBasic_ProductDefinitionRelationship.hxx>
45 #include <StepBasic_ProductDefinitionWithAssociatedDocuments.hxx>
46 #include <StepBasic_SiUnit.hxx>
47 #include <StepBasic_SiUnitAndLengthUnit.hxx>
48 #include <StepBasic_Unit.hxx>
49 #include <STEPCAFControl_Controller.hxx>
50 #include <STEPCAFControl_DataMapIteratorOfDataMapOfShapePD.hxx>
51 #include <STEPCAFControl_DataMapOfPDExternFile.hxx>
52 #include <STEPCAFControl_DataMapOfSDRExternFile.hxx>
53 #include <STEPCAFControl_DataMapOfShapePD.hxx>
54 #include <STEPCAFControl_ExternFile.hxx>
55 #include <STEPConstruct.hxx>
56 #include <STEPConstruct_Assembly.hxx>
57 #include <STEPConstruct_ExternRefs.hxx>
58 #include <STEPConstruct_Styles.hxx>
59 #include <STEPConstruct_Tool.hxx>
60 #include <STEPConstruct_UnitContext.hxx>
61 #include <STEPConstruct_ValidationProps.hxx>
62 #include <STEPControl_ActorRead.hxx>
63 #include <STEPControl_Reader.hxx>
64 #include <StepGeom_GeometricRepresentationItem.hxx>
65 #include <StepGeom_Axis2Placement3d.hxx>
66 #include <StepGeom_Direction.hxx>
67 #include <StepDimTol_AngularityTolerance.hxx>
68 #include <StepDimTol_CircularRunoutTolerance.hxx>
69 #include <StepDimTol_CoaxialityTolerance.hxx>
70 #include <StepDimTol_ConcentricityTolerance.hxx>
71 #include <StepDimTol_CylindricityTolerance.hxx>
72 #include <StepDimTol_Datum.hxx>
73 #include <StepDimTol_DatumFeature.hxx>
74 #include <StepDimTol_DatumReference.hxx>
75 #include <StepDimTol_DatumReferenceElement.hxx>
76 #include <StepDimTol_DatumReferenceCompartment.hxx>
77 #include <StepDimTol_DatumSystem.hxx>
78 #include <StepDimTol_FlatnessTolerance.hxx>
79 #include <StepDimTol_GeometricTolerance.hxx>
80 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
81 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
82 #include <StepDimTol_GeoTolAndGeoTolWthDatRef.hxx>
83 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol.hxx>
84 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol.hxx>
85 #include <StepDimTol_GeoTolAndGeoTolWthMaxTol.hxx>
86 #include <StepDimTol_HArray1OfDatumReference.hxx>
87 #include <StepDimTol_LineProfileTolerance.hxx>
88 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
89 #include <StepDimTol_ParallelismTolerance.hxx>
90 #include <StepDimTol_PerpendicularityTolerance.hxx>
91 #include <StepDimTol_PositionTolerance.hxx>
92 #include <StepDimTol_ProjectedZoneDefinition.hxx>
93 #include <StepDimTol_RoundnessTolerance.hxx>
94 #include <StepDimTol_RunoutZoneDefinition.hxx>
95 #include <StepDimTol_StraightnessTolerance.hxx>
96 #include <StepDimTol_SurfaceProfileTolerance.hxx>
97 #include <StepDimTol_SymmetryTolerance.hxx>
98 #include <StepDimTol_ToleranceZone.hxx>
99 #include <StepDimTol_ToleranceZoneForm.hxx>
100 #include <StepDimTol_TotalRunoutTolerance.hxx>
101 #include <StepDimTol_GeometricToleranceWithModifiers.hxx>
102 #include <StepDimTol_HArray1OfGeometricToleranceModifier.hxx>
103 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod.hxx>
104 #include <StepDimTol_GeoTolAndGeoTolWthMod.hxx>
105 #include <StepDimTol_GeometricToleranceWithMaximumTolerance.hxx>
106 #include <StepGeom_Axis2Placement3d.hxx>
107 #include <StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext.hxx>
108 #include <StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx.hxx>
109 #include <StepGeom_Plane.hxx>
110 #include <StepGeom_Polyline.hxx>
111 #include <StepDimTol_PlacedDatumTargetFeature.hxx>
112 #include <StepRepr_AssemblyComponentUsage.hxx>
113 #include <StepRepr_CharacterizedDefinition.hxx>
114 #include <StepRepr_CompoundRepresentationItem.hxx>
115 #include <StepRepr_DerivedShapeAspect.hxx>
116 #include <StepRepr_DescriptiveRepresentationItem.hxx>
117 #include <StepRepr_HArray1OfRepresentationItem.hxx>
118 #include <StepRepr_MappedItem.hxx>
119 #include <StepRepr_MeasureRepresentationItem.hxx>
120 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
121 #include <StepRepr_ProductDefinitionShape.hxx>
122 #include <StepRepr_PropertyDefinition.hxx>
123 #include <StepRepr_PropertyDefinitionRepresentation.hxx>
124 #include <StepRepr_Representation.hxx>
125 #include <StepRepr_RepresentationItem.hxx>
126 #include <StepRepr_HArray1OfRepresentationItem.hxx>
127 #include <StepRepr_RepresentationMap.hxx>
128 #include <StepRepr_RepresentationRelationship.hxx>
129 #include <StepRepr_RepresentedDefinition.hxx>
130 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
131 #include <StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI.hxx>
132 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnit.hxx>
133 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI.hxx>
134 #include <StepRepr_SequenceOfRepresentationItem.hxx>
135 #include <StepRepr_ShapeAspect.hxx>
136 #include <StepRepr_ShapeAspectDerivingRelationship.hxx>
137 #include <StepRepr_CompositeShapeAspect.hxx>
138 #include <StepRepr_AllAroundShapeAspect.hxx>
139 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
140 #include <StepRepr_ShapeAspectRelationship.hxx>
141 #include <StepRepr_ShapeRepresentationRelationship.hxx>
142 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
143 #include <StepRepr_ValueRange.hxx>
144 #include <StepRepr_FeatureForDatumTargetRelationship.hxx>
145 #include <StepShape_AdvancedFace.hxx>
146 #include <StepShape_AdvancedBrepShapeRepresentation.hxx>
147 #include <StepShape_AngleRelator.hxx>
148 #include <StepShape_AngularSize.hxx>
149 #include <StepShape_AngularLocation.hxx>
150 #include <StepShape_ClosedShell.hxx>
151 #include <StepShape_ConnectedFaceSet.hxx>
152 #include <StepShape_ContextDependentShapeRepresentation.hxx>
153 #include <StepRepr_CompGroupShAspAndCompShAspAndDatumFeatAndShAsp.hxx>
154 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
155 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
156 #include <StepShape_DimensionalSizeWithPath.hxx>
157 #include <StepShape_DimensionalLocationWithPath.hxx>
158 #include <StepShape_ShapeDimensionRepresentationItem.hxx>
159 #include <StepShape_ShapeRepresentationWithParameters.hxx>
160 #include <StepShape_HArray1OfShapeDimensionRepresentationItem.hxx>
161 #include <StepShape_DimensionalSize.hxx>
162 #include <StepShape_DimensionalLocation.hxx>
163 #include <StepShape_EdgeCurve.hxx>
164 #include <StepShape_EdgeLoop.hxx>
165 #include <StepShape_GeometricCurveSet.hxx>
166 #include <StepShape_GeometricSet.hxx>
167 #include <StepShape_HArray1OfFace.hxx>
168 #include <StepShape_HArray1OfFaceBound.hxx>
169 #include <StepShape_HArray1OfOrientedEdge.hxx>
170 #include <StepShape_HArray1OfShell.hxx>
171 #include <StepShape_LimitsAndFits.hxx>
172 #include <StepShape_Loop.hxx>
173 #include <StepShape_ManifoldSolidBrep.hxx>
174 #include <StepShape_PlusMinusTolerance.hxx>
175 #include <StepShape_QualifiedRepresentationItem.hxx>
176 #include <StepShape_OpenShell.hxx>
177 #include <StepShape_ShapeDefinitionRepresentation.hxx>
178 #include <StepShape_ShapeDimensionRepresentation.hxx>
179 #include <StepShape_ShapeRepresentation.hxx>
180 #include <StepShape_ShellBasedSurfaceModel.hxx>
181 #include <StepShape_SolidModel.hxx>
182 #include <StepShape_ToleranceMethodDefinition.hxx>
183 #include <StepShape_ToleranceValue.hxx>
184 #include <StepShape_ValueFormatTypeQualifier.hxx>
185 #include <StepShape_Vertex.hxx>
186 #include <StepToGeom.hxx>
187 #include <StepVisual_AnnotationCurveOccurrence.hxx>
188 #include <StepVisual_AnnotationFillArea.hxx>
189 #include <StepVisual_AnnotationPlane.hxx>
190 #include <StepVisual_CameraModelD3.hxx>
191 #include <StepVisual_CameraModelD3MultiClipping.hxx>
192 #include <StepVisual_CameraModelD3MultiClippingIntersection.hxx>
193 #include <StepVisual_CameraModelD3MultiClippingUnion.hxx>
194 #include <StepVisual_CoordinatesList.hxx>
195 #include <StepVisual_HArray1OfCameraModelD3MultiClippingInterectionSelect.hxx>
196 #include <StepVisual_HArray1OfCameraModelD3MultiClippingUnionSelect.hxx>
197 #include <StepVisual_DraughtingCallout.hxx>
198 #include <StepVisual_DraughtingCalloutElement.hxx>
199 #include <StepVisual_DraughtingModel.hxx>
200 #include <StepVisual_Invisibility.hxx>
201 #include <StepVisual_LayeredItem.hxx>
202 #include <StepVisual_PlanarBox.hxx>
203 #include <StepVisual_PresentationLayerAssignment.hxx>
204 #include <StepVisual_PresentationStyleByContext.hxx>
205 #include <StepVisual_StyleContextSelect.hxx>
206 #include <StepVisual_StyledItem.hxx>
207 #include <StepVisual_ViewVolume.hxx>
208 #include <StepShape_TypeQualifier.hxx>
209 #include <TCollection_AsciiString.hxx>
210 #include <TCollection_HAsciiString.hxx>
211 #include <TColStd_HArray1OfReal.hxx>
212 #include <TColStd_HArray1OfTransient.hxx>
213 #include <TColStd_HSequenceOfTransient.hxx>
214 #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
215 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
216 #include <TColStd_MapOfTransient.hxx>
217 #include <TColStd_SequenceOfHAsciiString.hxx>
218 #include <TDataStd_Name.hxx>
219 #include <TDataStd_TreeNode.hxx>
220 #include <TDataStd_UAttribute.hxx>
221 #include <TDF_Label.hxx>
222 #include <TDF_Tool.hxx>
223 #include <TDocStd_Document.hxx>
224 #include <TNaming_NamedShape.hxx>
225 #include <TopExp_Explorer.hxx>
226 #include <TopoDS.hxx>
227 #include <TopoDS_Compound.hxx>
228 #include <TopoDS_Iterator.hxx>
229 #include <TopoDS_Shape.hxx>
230 #include <TopTools_ListIteratorOfListOfShape.hxx>
231 #include <TopTools_ListOfShape.hxx>
232 #include <TopTools_MapOfShape.hxx>
233 #include <Transfer_Binder.hxx>
234 #include <Transfer_TransientProcess.hxx>
235 #include <TransferBRep.hxx>
236 #include <UnitsMethods.hxx>
237 #include <XCAFDoc.hxx>
238 #include <XCAFDoc_Area.hxx>
239 #include <XCAFDoc_Centroid.hxx>
240 #include <XCAFDoc_ClippingPlaneTool.hxx>
241 #include <XCAFDoc_ColorTool.hxx>
242 #include <XCAFDoc_DataMapOfShapeLabel.hxx>
243 #include <XCAFDoc_DimTolTool.hxx>
244 #include <XCAFDoc_Dimension.hxx>
245 #include <XCAFDoc_Datum.hxx>
246 #include <XCAFDoc_GeomTolerance.hxx>
247 #include <XCAFDoc_DocumentTool.hxx>
248 #include <XCAFDoc_GraphNode.hxx>
249 #include <XCAFDoc_LayerTool.hxx>
250 #include <XCAFDoc_MaterialTool.hxx>
251 #include <XCAFDoc_ShapeTool.hxx>
252 #include <XCAFDoc_View.hxx>
253 #include <XCAFDoc_ViewTool.hxx>
254 #include <XCAFDoc_Volume.hxx>
255 #include <XCAFDimTolObjects_DimensionModifiersSequence.hxx>
256 #include <XCAFDimTolObjects_GeomToleranceType.hxx>
257 #include <XCAFDimTolObjects_DimensionObject.hxx>
258 #include <XCAFDimTolObjects_GeomToleranceObject.hxx>
259 #include <XCAFDimTolObjects_DatumObject.hxx>
260 #include <XCAFView_Object.hxx>
261 #include <XSAlgo.hxx>
262 #include <XSAlgo_AlgoContainer.hxx>
263 #include <XSControl_TransferReader.hxx>
264 #include <XSControl_WorkSession.hxx>
265 #include <StepAP242_DraughtingModelItemAssociation.hxx>
266 #include <StepAP242_GeometricItemSpecificUsage.hxx>
267 #include <StepGeom_CartesianPoint.hxx>
268 #include <STEPCAFControl_GDTProperty.hxx>
269 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
270 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
271 #include <StepVisual_TessellatedItem.hxx>
272 #include <StepVisual_TessellatedGeometricSet.hxx>
273 #include <StepVisual_TessellatedCurveSet.hxx>
274 #include <StepVisual_CoordinatesList.hxx>
275 #include <NCollection_Vector.hxx>
276
277 #include <TColgp_HArray1OfXYZ.hxx>
278 #include <BRepBuilderAPI_MakeEdge.hxx>
279 #include <BRepTools.hxx>
280 #include <Transfer_ActorOfTransientProcess.hxx>
281 #include <Bnd_Box.hxx>
282 #include <BRepBndLib.hxx>
283 #include <Resource_Unicode.hxx>
284
285 // skl 21.08.2003 for reading G&DT
286 //#include <StepRepr_CompoundItemDefinition.hxx>
287 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
288 //#include <StepBasic_ConversionBasedUnit.hxx>
289 //#include <TDataStd_Real.hxx>
290 //#include <TDataStd_Constraint.hxx>
291 //#include <TDataStd_ConstraintEnum.hxx>
292 //#include <TNaming_Tool.hxx>
293 //#include <AIS_InteractiveObject.hxx>
294 //#include <TPrsStd_ConstraintTools.hxx>
295 //#include <AIS_DiameterDimension.hxx>
296 //#include <TPrsStd_Position.hxx>
297 //#include <TPrsStd_AISPresentation.hxx>
298 //#include <TNaming_Builder.hxx>
299 #ifdef OCCT_DEBUG
300 //! Converts address of the passed shape (TShape) to string.
301 //! \param theShape [in] Shape to dump.
302 //! \return corresponding string.
303 TCollection_AsciiString AddrToString(const TopoDS_Shape& theShape)
304 {
305   std::string anAddrStr;
306   std::ostringstream ost;
307   ost << theShape.TShape().get();
308   anAddrStr = ost.str();
309
310   TCollection_AsciiString aStr =
311     TCollection_AsciiString("[").Cat(anAddrStr.c_str()).Cat("]");
312
313   return aStr;
314 }
315 #endif
316
317 //=======================================================================
318 //function : STEPCAFControl_Reader
319 //purpose  : 
320 //=======================================================================
321
322 STEPCAFControl_Reader::STEPCAFControl_Reader()
323 : mySourceCodePage (Resource_FormatType_UTF8),
324   myColorMode(Standard_True),
325   myNameMode(Standard_True),
326   myLayerMode(Standard_True),
327   myPropsMode(Standard_True),
328   mySHUOMode(Standard_False),
329   myGDTMode(Standard_True),
330   myMatMode(Standard_True),
331   myViewMode(Standard_True)
332 {
333   STEPCAFControl_Controller::Init();
334   mySourceCodePage = (Resource_FormatType )Interface_Static::IVal ("read.stepcaf.codepage");
335 }
336
337
338 //=======================================================================
339 //function : STEPCAFControl_Reader
340 //purpose  : 
341 //=======================================================================
342
343 STEPCAFControl_Reader::STEPCAFControl_Reader(const Handle(XSControl_WorkSession)& WS,
344   const Standard_Boolean scratch)
345 : mySourceCodePage (Resource_FormatType_UTF8),
346   myColorMode(Standard_True),
347   myNameMode(Standard_True),
348   myLayerMode(Standard_True),
349   myPropsMode(Standard_True),
350   mySHUOMode(Standard_False),
351   myGDTMode(Standard_True),
352   myMatMode(Standard_True),
353   myViewMode(Standard_True)
354 {
355   STEPCAFControl_Controller::Init();
356   mySourceCodePage = (Resource_FormatType )Interface_Static::IVal ("read.stepcaf.codepage");
357   Init(WS, scratch);
358 }
359
360 //=======================================================================
361 //function : ~STEPCAFControl_Reader
362 //purpose  :
363 //=======================================================================
364 STEPCAFControl_Reader::~STEPCAFControl_Reader()
365 {
366   //
367 }
368
369 //=======================================================================
370 //function : Init
371 //purpose  : 
372 //=======================================================================
373
374 void STEPCAFControl_Reader::Init(const Handle(XSControl_WorkSession)& WS,
375   const Standard_Boolean scratch)
376 {
377   // necessary only in Writer, to set good actor:  WS->SelectNorm ( "STEP" );
378   myReader.SetWS(WS, scratch);
379   myFiles.Clear();
380 }
381
382 //=======================================================================
383 //function : convertName
384 //purpose  :
385 //=======================================================================
386 TCollection_ExtendedString STEPCAFControl_Reader::convertName (const TCollection_AsciiString& theName) const
387 {
388   TCollection_ExtendedString aName;
389   Resource_Unicode::ConvertFormatToUnicode (mySourceCodePage, theName.ToCString(), aName);
390   return aName;
391 }
392
393 //=======================================================================
394 //function : ReadFile
395 //purpose  : 
396 //=======================================================================
397
398 IFSelect_ReturnStatus STEPCAFControl_Reader::ReadFile(const Standard_CString filename)
399 {
400   return myReader.ReadFile(filename);
401 }
402
403
404 //=======================================================================
405 //function : NbRootsForTransfer
406 //purpose  : 
407 //=======================================================================
408
409 Standard_Integer STEPCAFControl_Reader::NbRootsForTransfer()
410 {
411   return myReader.NbRootsForTransfer();
412 }
413
414
415 //=======================================================================
416 //function : TransferOneRoot
417 //purpose  : 
418 //=======================================================================
419
420 Standard_Boolean STEPCAFControl_Reader::TransferOneRoot (const Standard_Integer num,
421                                                          Handle(TDocStd_Document) &doc,
422                                                          const Message_ProgressRange& theProgress)
423 {
424   TDF_LabelSequence Lseq;
425   return Transfer (myReader, num, doc, Lseq, Standard_False, theProgress);
426 }
427
428
429 //=======================================================================
430 //function : Transfer
431 //purpose  : 
432 //=======================================================================
433
434 Standard_Boolean STEPCAFControl_Reader::Transfer (Handle(TDocStd_Document) &doc,
435                                                   const Message_ProgressRange& theProgress)
436 {
437   TDF_LabelSequence Lseq;
438   return Transfer (myReader, 0, doc, Lseq, Standard_False, theProgress);
439 }
440
441
442 //=======================================================================
443 //function : Perform
444 //purpose  : 
445 //=======================================================================
446
447 Standard_Boolean STEPCAFControl_Reader::Perform (const Standard_CString filename,
448                                                  Handle(TDocStd_Document) &doc,
449                                                  const Message_ProgressRange& theProgress)
450 {
451   if (ReadFile (filename) != IFSelect_RetDone)
452   {
453     return Standard_False;
454   }
455   return Transfer (doc, theProgress);
456 }
457
458
459 //=======================================================================
460 //function : Perform
461 //purpose  : 
462 //=======================================================================
463
464 Standard_Boolean STEPCAFControl_Reader::Perform (const TCollection_AsciiString &filename,
465                                                  Handle(TDocStd_Document) &doc,
466                                                  const Message_ProgressRange& theProgress)
467 {
468   if ( ReadFile (filename.ToCString()) != IFSelect_RetDone)
469   {
470     return Standard_False;
471   }
472   return Transfer (doc, theProgress);
473 }
474
475
476 //=======================================================================
477 //function : ExternFiles
478 //purpose  : 
479 //=======================================================================
480
481 const   NCollection_DataMap<TCollection_AsciiString, Handle(STEPCAFControl_ExternFile)>& STEPCAFControl_Reader::ExternFiles() const
482 {
483   return myFiles;
484 }
485
486
487 //=======================================================================
488 //function : ExternFile
489 //purpose  : 
490 //=======================================================================
491
492 Standard_Boolean STEPCAFControl_Reader::ExternFile(const Standard_CString name,
493   Handle(STEPCAFControl_ExternFile) &ef) const
494 {
495   ef.Nullify();
496   if (myFiles.IsEmpty() || !myFiles.IsBound(name))
497     return Standard_False;
498   ef = myFiles.Find(name);
499   return Standard_True;
500 }
501
502
503 //=======================================================================
504 //function : Reader
505 //purpose  : 
506 //=======================================================================
507
508 STEPControl_Reader &STEPCAFControl_Reader::ChangeReader()
509 {
510   return myReader;
511 }
512
513
514 //=======================================================================
515 //function : Reader
516 //purpose  : 
517 //=======================================================================
518
519 const STEPControl_Reader &STEPCAFControl_Reader::Reader() const
520 {
521   return myReader;
522 }
523
524
525 //=======================================================================
526 //function : FillShapesMap
527 //purpose  : auxiliary: fill a map by all compounds and their components
528 //=======================================================================
529
530 static void FillShapesMap(const TopoDS_Shape &S, TopTools_MapOfShape &map)
531 {
532   TopoDS_Shape S0 = S;
533   TopLoc_Location loc;
534   S0.Location(loc);
535   map.Add(S0);
536   if (S.ShapeType() != TopAbs_COMPOUND) return;
537   for (TopoDS_Iterator it(S); it.More(); it.Next())
538     FillShapesMap(it.Value(), map);
539 }
540
541
542 //=======================================================================
543 //function : Transfer
544 //purpose  : basic working method
545 //=======================================================================
546
547 Standard_Boolean STEPCAFControl_Reader::Transfer (STEPControl_Reader &reader,
548                                                   const Standard_Integer nroot,
549                                                   Handle(TDocStd_Document) &doc,
550                                                   TDF_LabelSequence &Lseq,
551                                                   const Standard_Boolean asOne,
552                                                   const Message_ProgressRange& theProgress)
553 {
554   reader.ClearShapes();
555   Standard_Integer i;
556
557   // Read all shapes
558   Standard_Integer num = reader.NbRootsForTransfer();
559   if (num <=0) return Standard_False;
560
561   Message_ProgressScope aPSRoot (theProgress, NULL, 2);
562
563   if (nroot) {
564     if (nroot > num) return Standard_False;
565     reader.TransferOneRoot (nroot, aPSRoot.Next());
566   }
567   else {
568     Message_ProgressScope aPS (aPSRoot.Next(), NULL, num);
569     for (i = 1; i <= num && aPS.More(); i++)
570       reader.TransferOneRoot (i, aPS.Next());
571   }
572   if (aPSRoot.UserBreak())
573     return Standard_False;
574
575   num = reader.NbShapes();
576   if (num <= 0) return Standard_False;
577
578   // Fill a map of (top-level) shapes resulting from that transfer
579   // Only these shapes will be considered further
580   TopTools_MapOfShape ShapesMap, NewShapesMap;
581   for (i = 1; i <= num; i++) FillShapesMap(reader.Shape(i), ShapesMap);
582
583   // Collect information on shapes originating from SDRs
584   // this will be used to distinguish compounds representing assemblies
585   // from the ones representing hybrid models and shape sets
586   STEPCAFControl_DataMapOfShapePD ShapePDMap;
587   STEPCAFControl_DataMapOfPDExternFile PDFileMap;
588   Handle(Interface_InterfaceModel) Model = reader.Model();
589   const Handle(Transfer_TransientProcess) &TP = reader.WS()->TransferReader()->TransientProcess();
590   Standard_Integer nb = Model->NbEntities();
591
592   Handle(TColStd_HSequenceOfTransient) SeqPDS = new TColStd_HSequenceOfTransient;
593
594   for (i = 1; i <= nb; i++) {
595     Handle(Standard_Transient) enti = Model->Value(i);
596     if (enti->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) {
597       // sequence for acceleration ReadMaterials
598       SeqPDS->Append(enti);
599     }
600     if (enti->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition))) {
601       Handle(StepBasic_ProductDefinition) PD =
602         Handle(StepBasic_ProductDefinition)::DownCast(enti);
603       Standard_Integer index = TP->MapIndex(PD);
604       if (index > 0) {
605         Handle(Transfer_Binder) binder = TP->MapItem(index);
606         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
607         if (!S.IsNull() && ShapesMap.Contains(S)) {
608           NewShapesMap.Add(S);
609           ShapePDMap.Bind(S, PD);
610           Handle(STEPCAFControl_ExternFile) EF;
611           PDFileMap.Bind(PD, EF);
612         }
613       }
614     }
615     if (enti->IsKind(STANDARD_TYPE(StepShape_ShapeRepresentation))) {
616       Standard_Integer index = TP->MapIndex(enti);
617       if (index > 0) {
618         Handle(Transfer_Binder) binder = TP->MapItem(index);
619         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
620         if (!S.IsNull() && ShapesMap.Contains(S))
621           NewShapesMap.Add(S);
622       }
623     }
624   }
625
626   // get directory name of the main file
627   OSD_Path mainfile(reader.WS()->LoadedFile());
628   mainfile.SetName("");
629   mainfile.SetExtension("");
630   TCollection_AsciiString dpath;
631   mainfile.SystemName(dpath);
632
633   // Load external references (only for relevant SDRs)
634   // and fill map SDR -> extern file
635   STEPConstruct_ExternRefs ExtRefs(reader.WS());
636   ExtRefs.LoadExternRefs();
637   Message_ProgressScope aPSE (aPSRoot.Next(), NULL, ExtRefs.NbExternRefs());
638   for (i = 1; i <= ExtRefs.NbExternRefs() && aPSE.More(); i++)
639   {
640     Message_ProgressRange aRange = aPSE.Next();
641     // check extern ref format
642     Handle(TCollection_HAsciiString) format = ExtRefs.Format(i);
643     if (!format.IsNull()) {
644       static Handle(TCollection_HAsciiString) ap203 = new TCollection_HAsciiString("STEP AP203");
645       static Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString("STEP AP214");
646       if (!format->IsSameString(ap203, Standard_False) &&
647         !format->IsSameString(ap214, Standard_False)) {
648 #ifdef OCCT_DEBUG
649         std::cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document is neither STEP AP203 nor AP214" << std::endl;
650 #else
651         continue;
652 #endif
653       }
654     }
655 #ifdef OCCT_DEBUG
656     else std::cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document format not defined" << std::endl;
657 #endif
658
659     // get and check filename of the current extern ref
660     const Standard_CString filename = ExtRefs.FileName(i);
661
662 #ifdef OCCT_DEBUG
663     std::cout << "filename=" << filename << std::endl;
664 #endif
665
666     if (!filename || !filename[0]) {
667 #ifdef OCCT_DEBUG
668       std::cout << "Warning: STEPCAFControl_Reader::Transfer: Extern reference file name is empty" << std::endl;
669 #endif
670       continue; // not a valid extern ref
671     }
672
673     // compute true path to the extern file
674     TCollection_AsciiString fullname = OSD_Path::AbsolutePath(dpath, filename);
675     if (fullname.Length() <= 0) fullname = filename;
676
677     /*
678         char fullname[1024];
679         char *mainfile = reader.WS()->LoadedFile();
680         if ( ! mainfile ) mainfile = "";
681         Standard_Integer slash = 0;
682         for ( Standard_Integer k=0; mainfile[k]; k++ )
683           if ( mainfile[k] == '/' ) slash = k;
684         strncpy ( fullname, mainfile, slash );
685         sprintf ( &fullname[slash], "%s%s", ( mainfile[0] ? "/" : "" ), filename );
686     */
687
688     // get and check PD associated with the current extern ref
689     Handle(StepBasic_ProductDefinition) PD = ExtRefs.ProdDef(i);
690     if (PD.IsNull()) continue; // not a valid extern ref
691     if (!PDFileMap.IsBound(PD)) continue; // this PD is not concerned by current transfer
692
693     // read extern file (or use existing data) and record its data
694     Handle(STEPCAFControl_ExternFile) EF = 
695       ReadExternFile (filename, fullname.ToCString(), doc, aRange);
696     PDFileMap.Bind (PD, EF);
697   }
698
699   // and insert them to the document
700   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool(doc->Main());
701   if (STool.IsNull()) return Standard_False;
702   XCAFDoc_DataMapOfShapeLabel map;
703   if (asOne)
704     Lseq.Append(AddShape(reader.OneShape(), STool, NewShapesMap, ShapePDMap, PDFileMap, map));
705   else {
706     for (i = 1; i <= num; i++) {
707       Lseq.Append(AddShape(reader.Shape(i), STool, NewShapesMap, ShapePDMap, PDFileMap, map));
708     }
709   }
710
711   // read colors
712   if (GetColorMode())
713     ReadColors(reader.WS(), doc, map);
714
715   // read names
716   if (GetNameMode())
717     ReadNames(reader.WS(), doc, PDFileMap, map);
718
719   // read validation props
720   if (GetPropsMode())
721     ReadValProps(reader.WS(), doc, PDFileMap, map);
722
723   // read layers
724   if (GetLayerMode())
725     ReadLayers(reader.WS(), doc);
726
727   // read SHUO entities from STEP model
728   if (GetSHUOMode())
729     ReadSHUOs(reader.WS(), doc, PDFileMap, map);
730
731   // read GDT entities from STEP model
732   if (GetGDTMode())
733     ReadGDTs(reader.WS(), doc);
734
735   // read Material entities from STEP model
736   if (GetMatMode())
737     ReadMaterials(reader.WS(), doc, SeqPDS);
738
739   // read View entities from STEP model
740   if (GetViewMode())
741     ReadViews(reader.WS(), doc);
742
743   // Expand resulting CAF structure for sub-shapes (optionally with their
744   // names) if requested
745   ExpandSubShapes(STool, map, ShapePDMap);
746
747   // Update assembly compounds
748   STool->UpdateAssemblies();
749
750   return Standard_True;
751 }
752
753 //=======================================================================
754 //function : AddShape
755 //purpose  : 
756 //=======================================================================
757
758 TDF_Label STEPCAFControl_Reader::AddShape(const TopoDS_Shape &S,
759   const Handle(XCAFDoc_ShapeTool) &STool,
760   const TopTools_MapOfShape &NewShapesMap,
761   const STEPCAFControl_DataMapOfShapePD &ShapePDMap,
762   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
763   XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
764 {
765   // if shape has already been mapped, just return corresponding label
766   if (ShapeLabelMap.IsBound(S)) {
767     return ShapeLabelMap.Find(S);
768   }
769
770   // if shape is located, create instance
771   if (!S.Location().IsIdentity()) {
772     TopoDS_Shape S0 = S;
773     TopLoc_Location loc;
774     S0.Location(loc);
775     AddShape(S0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap);
776     TDF_Label L = STool->AddShape(S, Standard_False); // should create reference
777     ShapeLabelMap.Bind(S, L);
778     return L;
779   }
780
781   // if shape is not compound, simple add it
782   if (S.ShapeType() != TopAbs_COMPOUND) {
783     TDF_Label L = STool->AddShape(S, Standard_False);
784     ShapeLabelMap.Bind(S, L);
785     return L;
786   }
787
788   // for compounds, compute number of subshapes and check whether this is assembly
789   Standard_Boolean isAssembly = Standard_False;
790   Standard_Integer nbComponents = 0;
791   TopoDS_Iterator it;
792   for (it.Initialize(S); it.More() && !isAssembly; it.Next(), nbComponents++) {
793     TopoDS_Shape Sub0 = it.Value();
794     TopLoc_Location loc;
795     Sub0.Location(loc);
796     if (NewShapesMap.Contains(Sub0)) isAssembly = Standard_True;
797   }
798
799   //  if(nbComponents>0) isAssembly = Standard_True;
800
801     // check whether it has associated external ref
802   TColStd_SequenceOfHAsciiString SHAS;
803   if (ShapePDMap.IsBound(S) && PDFileMap.IsBound(ShapePDMap.Find(S))) {
804     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find(ShapePDMap.Find(S));
805     if (!EF.IsNull()) {
806       // (store information on extern refs in the document)
807       SHAS.Append(EF->GetName());
808       // if yes, just return corresponding label
809       if (!EF->GetLabel().IsNull()) {
810         // but if components >0, ignore extern ref!
811         if (nbComponents <= 0) {
812           ShapeLabelMap.Bind(S, EF->GetLabel());
813           STool->SetExternRefs(EF->GetLabel(), SHAS);
814           return EF->GetLabel();
815         }
816       }
817 #ifdef OCCT_DEBUG
818       if (!EF->GetLabel().IsNull())
819         std::cout << "Warning: STEPCAFControl_Reader::AddShape: Non-empty shape with external ref; ref is ignored" << std::endl;
820       else if (nbComponents <= 0)
821         std::cout << "Warning: STEPCAFControl_Reader::AddShape: Result of reading extern ref is Null" << std::endl;
822 #endif
823     }
824   }
825
826   // add compound either as a whole,
827   if (!isAssembly) {
828     TDF_Label L = STool->AddShape(S, Standard_False);
829     if (SHAS.Length() > 0) STool->SetExternRefs(L, SHAS);
830     ShapeLabelMap.Bind(S, L);
831     return L;
832   }
833
834   // or as assembly, component-by-component
835   TDF_Label L = STool->NewShape();
836   nbComponents = 0;
837   for (it.Initialize(S); it.More(); it.Next(), nbComponents++) {
838     TopoDS_Shape Sub0 = it.Value();
839     TopLoc_Location loc;
840     Sub0.Location(loc);
841     TDF_Label subL = AddShape(Sub0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap);
842     if (!subL.IsNull()) {
843       TDF_Label instL = STool->AddComponent(L, subL, it.Value().Location());
844       if (!ShapeLabelMap.IsBound(it.Value())) {
845         ShapeLabelMap.Bind(it.Value(), instL);
846       }
847     }
848   }
849   if (SHAS.Length() > 0) STool->SetExternRefs(L, SHAS);
850   ShapeLabelMap.Bind(S, L);
851   //STool->SetShape ( L, S ); // it is necessary for assemblies OCC1747 // commemted by skl for OCC2941
852
853   return L;
854 }
855
856 //=======================================================================
857 //function : ReadExternFile
858 //purpose  : 
859 //=======================================================================
860
861 Handle(STEPCAFControl_ExternFile) STEPCAFControl_Reader::ReadExternFile (const Standard_CString file, 
862                                                                          const Standard_CString fullname,
863                                                                          Handle(TDocStd_Document)& doc,
864                                                                          const Message_ProgressRange& theProgress)
865 {
866   // if the file is already read, associate it with SDR
867   if (myFiles.IsBound(file)) {
868     return myFiles.ChangeFind(file);
869   }
870
871 #ifdef OCCT_DEBUG
872   std::cout << "Reading extern file: " << fullname << std::endl;
873 #endif
874
875   // create new WorkSession and Reader
876   Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
877   newWS->SelectNorm("STEP");
878   STEPControl_Reader sr(newWS, Standard_False);
879
880   // start to fill the resulting ExternFile structure
881   Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
882   EF->SetWS(newWS);
883   EF->SetName(new TCollection_HAsciiString(file));
884
885   // read file
886   EF->SetLoadStatus(sr.ReadFile(fullname));
887
888   // transfer in single-result mode
889   if (EF->GetLoadStatus() == IFSelect_RetDone) {
890     TDF_LabelSequence labels;
891     EF->SetTransferStatus (Transfer (sr, 0, doc, labels, Standard_False, theProgress));
892     if (labels.Length() > 0) EF->SetLabel (labels.Value(1));
893   }
894
895   // add read file to dictionary
896   myFiles.Bind(file, EF);
897
898   return EF;
899 }
900
901 //=======================================================================
902 //function : findStyledSR
903 //purpose  : auxilary
904 //=======================================================================
905 static void findStyledSR(const Handle(StepVisual_StyledItem) &style,
906   Handle(StepShape_ShapeRepresentation)& aSR)
907 {
908   // search Shape Represenatation for component styled item
909   for (Standard_Integer j = 1; j <= style->NbStyles(); j++) {
910     Handle(StepVisual_PresentationStyleByContext) PSA =
911       Handle(StepVisual_PresentationStyleByContext)::DownCast(style->StylesValue(j));
912     if (PSA.IsNull())
913       continue;
914     StepVisual_StyleContextSelect aStyleCntxSlct = PSA->StyleContext();
915     Handle(StepShape_ShapeRepresentation) aCurrentSR =
916       Handle(StepShape_ShapeRepresentation)::DownCast(aStyleCntxSlct.Representation());
917     if (aCurrentSR.IsNull())
918       continue;
919     aSR = aCurrentSR;
920     break;
921   }
922 }
923
924
925 //=======================================================================
926 //function : propagateColorToParts
927 //purpose  : auxilary, propagate color styles from assemblies to parts
928 //=======================================================================
929
930 static void propagateColorToParts(const Handle(XCAFDoc_ShapeTool)& theSTool,
931                                   const Handle(XCAFDoc_ColorTool)& theCTool,
932                                   const TDF_Label& theRoot)
933 {
934   // collect components to propagate
935   TDF_LabelSequence aComponents;
936   if (theRoot.IsEqual(theSTool->Label()))
937     theSTool->GetFreeShapes(aComponents);
938   else
939     theSTool->GetComponents(theRoot, aComponents);
940
941   // iterate each component
942   for (TDF_LabelSequence::Iterator anIt(aComponents); anIt.More(); anIt.Next())
943   {
944     // get original label
945     TDF_Label anOriginalL = anIt.Value();
946     theSTool->GetReferredShape(anOriginalL, anOriginalL);
947
948     // propagate to components without own colors
949     TDF_Label aColorL, aDummyColorL;
950     for (Standard_Integer aType = 1; aType <= 3; aType++)
951     {
952       if (theCTool->GetColor(theRoot, (XCAFDoc_ColorType)aType, aColorL) &&
953           !theCTool->GetColor(anOriginalL, (XCAFDoc_ColorType)aType, aDummyColorL))
954         theCTool->SetColor(anOriginalL, aColorL, (XCAFDoc_ColorType)aType);
955     }
956     if (!theCTool->IsVisible(theRoot))
957       theCTool->SetVisibility(anOriginalL, Standard_False);
958
959     // propagate to next level children
960     if (theSTool->IsAssembly(anOriginalL))
961       propagateColorToParts(theSTool, theCTool, anOriginalL);
962   }
963 }
964 //=======================================================================
965 //function : ReadColors
966 //purpose  : 
967 //=======================================================================
968
969 Standard_Boolean STEPCAFControl_Reader::ReadColors(const Handle(XSControl_WorkSession) &WS,
970   Handle(TDocStd_Document)& Doc,
971   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
972 {
973   STEPConstruct_Styles Styles(WS);
974   if (!Styles.LoadStyles()) {
975 #ifdef OCCT_DEBUG
976     std::cout << "Warning: no styles are found in the model" << std::endl;
977 #endif
978     return Standard_False;
979   }
980   // searching for invisible items in the model
981   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
982   Styles.LoadInvisStyles(aHSeqOfInvisStyle);
983
984   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool(Doc->Main());
985   if (CTool.IsNull()) return Standard_False;
986   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool(Doc->Main());
987   if (STool.IsNull()) return Standard_False;
988
989   // parse and search for color attributes
990   Standard_Integer nb = Styles.NbStyles();
991   for (Standard_Integer i = 1; i <= nb; i++) {
992     Handle(StepVisual_StyledItem) style = Styles.Style(i);
993     if (style.IsNull()) continue;
994
995     Standard_Boolean IsVisible = Standard_True;
996     // check the visibility of styled item.
997     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++) {
998       if (style != aHSeqOfInvisStyle->Value(si))
999         continue;
1000       // found that current style is invisible.
1001       IsVisible = Standard_False;
1002       break;
1003     }
1004
1005     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol, RenderCol;
1006     Standard_Real RenderTransp;
1007     // check if it is component style
1008     Standard_Boolean IsComponent = Standard_False;
1009     if (!Styles.GetColors(style, SurfCol, BoundCol, CurveCol, RenderCol, RenderTransp, IsComponent) && IsVisible)
1010       continue;
1011
1012     // collect styled items
1013     NCollection_Vector<StepVisual_StyledItemTarget> anItems;
1014     if (!style->ItemAP242().IsNull()) {
1015       anItems.Append(style->ItemAP242());
1016     }
1017
1018     const Handle(Transfer_TransientProcess) &TP = WS->TransferReader()->TransientProcess();
1019     for (Standard_Integer itemIt = 0; itemIt < anItems.Length(); itemIt++) {
1020       Standard_Integer index = TP->MapIndex(anItems.Value(itemIt).Value());
1021       TopoDS_Shape S;
1022       if (index > 0) {
1023         Handle(Transfer_Binder) binder = TP->MapItem(index);
1024         S = TransferBRep::ShapeResult(binder);
1025       }
1026       Standard_Boolean isSkipSHUOstyle = Standard_False;
1027       // take shape with real location.
1028       while (IsComponent) {
1029         // take SR of NAUO
1030         Handle(StepShape_ShapeRepresentation) aSR;
1031         findStyledSR(style, aSR);
1032         // search for SR along model
1033         if (aSR.IsNull())
1034           break;
1035         Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(aSR);
1036         Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1037         for (subs.Start(); subs.More(); subs.Next()) {
1038           aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1039           if (aSDR.IsNull())
1040             continue;
1041           StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1042           Handle(StepRepr_ProductDefinitionShape) PDS =
1043             Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1044           if (PDS.IsNull())
1045             continue;
1046           StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1047
1048           Handle(StepRepr_AssemblyComponentUsage) ACU =
1049             Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
1050           if (ACU.IsNull())
1051             continue;
1052           // PTV 10.02.2003 skip styled item that refer to SHUO
1053           if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1054             isSkipSHUOstyle = Standard_True;
1055             break;
1056           }
1057           Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
1058             Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
1059           if (NAUO.IsNull())
1060             continue;
1061
1062           TopoDS_Shape aSh;
1063           // PTV 10.02.2003 to find component of assembly CORRECTLY
1064           STEPConstruct_Tool Tool(WS);
1065           TDF_Label aShLab = FindInstance(NAUO, CTool->ShapeTool(), Tool, ShapeLabelMap);
1066           aSh = CTool->ShapeTool()->GetShape(aShLab);
1067           if (!aSh.IsNull()) {
1068             S = aSh;
1069             break;
1070           }
1071         }
1072         break;
1073       }
1074       if (isSkipSHUOstyle)
1075         continue; // skip styled item which refer to SHUO
1076
1077       if (S.IsNull())
1078         continue;
1079
1080       if (!SurfCol.IsNull() || !BoundCol.IsNull() || !CurveCol.IsNull() || !RenderCol.IsNull() || !IsVisible)
1081       {
1082         TDF_Label aL;
1083         Standard_Boolean isFound = STool->SearchUsingMap(S, aL, Standard_False, Standard_True);
1084         if (!SurfCol.IsNull() || !BoundCol.IsNull() || !CurveCol.IsNull() || !RenderCol.IsNull())
1085         {
1086           Quantity_Color aSCol, aBCol, aCCol, aRCol;
1087           Quantity_ColorRGBA aFullSCol;
1088           if (!SurfCol.IsNull()) {
1089             Styles.DecodeColor(SurfCol, aSCol);
1090             aFullSCol = Quantity_ColorRGBA(aSCol);
1091           }
1092           if (!BoundCol.IsNull())
1093             Styles.DecodeColor(BoundCol, aBCol);
1094           if (!CurveCol.IsNull())
1095             Styles.DecodeColor(CurveCol, aCCol);
1096           if (!RenderCol.IsNull()) {
1097             Styles.DecodeColor(RenderCol, aRCol);
1098             aFullSCol = Quantity_ColorRGBA(aRCol, static_cast<float>(1.0f - RenderTransp));
1099           }
1100           if (isFound)
1101           {
1102             if (!SurfCol.IsNull() || !RenderCol.IsNull())
1103               CTool->SetColor(aL, aFullSCol, XCAFDoc_ColorSurf);
1104             if (!BoundCol.IsNull())
1105               CTool->SetColor(aL, aBCol, XCAFDoc_ColorCurv);
1106             if (!CurveCol.IsNull())
1107               CTool->SetColor(aL, aCCol, XCAFDoc_ColorCurv);
1108           }
1109           else
1110           {
1111             for (TopoDS_Iterator it(S); it.More(); it.Next())
1112             {
1113               TDF_Label aL1;
1114               if (STool->SearchUsingMap(it.Value(), aL1, Standard_False, Standard_True))
1115               {
1116                 if (!SurfCol.IsNull() || !RenderCol.IsNull())
1117                   CTool->SetColor(aL1, aFullSCol, XCAFDoc_ColorSurf);
1118                 if (!BoundCol.IsNull())
1119                   CTool->SetColor(aL1, aBCol, XCAFDoc_ColorCurv);
1120                 if (!CurveCol.IsNull())
1121                   CTool->SetColor(aL1, aCCol, XCAFDoc_ColorCurv);
1122               }
1123             }
1124           }
1125         }
1126         if (!IsVisible)
1127         {
1128           // sets the invisibility for shape.
1129           if (isFound)
1130             CTool->SetVisibility(aL, Standard_False);
1131         }
1132       }
1133     }
1134   }
1135   CTool->ReverseChainsOfTreeNodes();
1136
1137   // some colors can be attached to assemblies, propagate them to components
1138   propagateColorToParts(STool, CTool, STool->Label());
1139   return Standard_True;
1140 }
1141
1142 //=======================================================================
1143 //function : GetLabelFromPD
1144 //purpose  : 
1145 //=======================================================================
1146
1147 static TDF_Label GetLabelFromPD(const Handle(StepBasic_ProductDefinition) &PD,
1148   const Handle(XCAFDoc_ShapeTool) &STool,
1149   const Handle(Transfer_TransientProcess) &TP,
1150   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1151   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1152 {
1153   TDF_Label L;
1154   if (PDFileMap.IsBound(PD)) {
1155     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find(PD);
1156     if (!EF.IsNull()) {
1157       L = EF->GetLabel();
1158       if (!L.IsNull()) return L;
1159     }
1160   }
1161
1162   TopoDS_Shape S;
1163   Handle(Transfer_Binder) binder = TP->Find(PD);
1164   if (binder.IsNull() || !binder->HasResult()) return L;
1165   S = TransferBRep::ShapeResult(TP, binder);
1166   if (S.IsNull()) return L;
1167
1168   if (ShapeLabelMap.IsBound(S))
1169     L = ShapeLabelMap.Find(S);
1170   if (L.IsNull())
1171     STool->Search(S, L, Standard_True, Standard_True, Standard_False);
1172   return L;
1173 }
1174
1175 //=======================================================================
1176 //function : FindInstance
1177 //purpose  : 
1178 //=======================================================================
1179
1180 TDF_Label STEPCAFControl_Reader::FindInstance(const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
1181   const Handle(XCAFDoc_ShapeTool) &STool,
1182   const STEPConstruct_Tool &Tool,
1183   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1184 {
1185   TDF_Label L;
1186
1187   // get shape resulting from CDSR (in fact, only location is interesting)
1188   Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
1189   Handle(Transfer_Binder) binder = TP->Find(NAUO);
1190   if (binder.IsNull() || !binder->HasResult()) {
1191 #ifdef OCCT_DEBUG
1192     std::cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << std::endl;
1193 #endif
1194     return L;
1195   }
1196
1197   TopoDS_Shape S = TransferBRep::ShapeResult(TP, binder);
1198   if (S.IsNull()) {
1199 #ifdef OCCT_DEBUG
1200     std::cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << std::endl;
1201 #endif
1202     return L;
1203   }
1204
1205   if (ShapeLabelMap.IsBound(S))
1206     L = ShapeLabelMap(S);
1207   else
1208     STool->Search(S, L, Standard_True, Standard_True, Standard_False);
1209
1210   return L;
1211 }
1212
1213 //=======================================================================
1214 //function : ReadNames
1215 //purpose  : 
1216 //=======================================================================
1217
1218 Standard_Boolean STEPCAFControl_Reader::ReadNames(const Handle(XSControl_WorkSession) &WS,
1219   Handle(TDocStd_Document)& Doc,
1220   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1221   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1222 {
1223   // get starting data
1224   const Handle(Interface_InterfaceModel) &Model = WS->Model();
1225   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
1226   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
1227   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool(Doc->Main());
1228   if (STool.IsNull()) return Standard_False;
1229   STEPConstruct_Tool Tool(WS);
1230
1231   // iterate on model to find all SDRs and CDSRs
1232   Standard_Integer nb = Model->NbEntities();
1233   Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
1234   Handle(Standard_Type) tPD = STANDARD_TYPE(StepBasic_ProductDefinition);
1235   Handle(Standard_Type) tPDWAD = STANDARD_TYPE(StepBasic_ProductDefinitionWithAssociatedDocuments);
1236   Handle(TCollection_HAsciiString) name;
1237   TDF_Label L;
1238   for (Standard_Integer i = 1; i <= nb; i++) {
1239     Handle(Standard_Transient) enti = Model->Value(i);
1240
1241     // get description of NAUO
1242     if (enti->DynamicType() == tNAUO) {
1243       L.Nullify();
1244       Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
1245         Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
1246       if (NAUO.IsNull()) continue;
1247       Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
1248       for (subs.Start(); subs.More(); subs.Next()) {
1249         Handle(StepRepr_ProductDefinitionShape) PDS =
1250           Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1251         if (PDS.IsNull()) continue;
1252         Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
1253         if (PDR.IsNull()) continue;
1254         if (PDR->HasDescription() &&
1255           PDR->Description()->UsefullLength() > 0) name = PDR->Description();
1256         else if (!PDR->Name().IsNull() && PDR->Name()->UsefullLength() > 0) name = PDR->Name();
1257         else if (!PDR->Id().IsNull()) name = PDR->Id();
1258         else name = new TCollection_HAsciiString;
1259       }
1260       // find proper label
1261       L = FindInstance(NAUO, STool, Tool, ShapeLabelMap);
1262       if (L.IsNull()) continue;
1263
1264       TCollection_ExtendedString str = convertName (name->String());
1265       TDataStd_Name::Set(L, str);
1266     }
1267
1268     // for PD get name of associated product
1269     if (enti->DynamicType() == tPD || enti->DynamicType() == tPDWAD) {
1270       L.Nullify();
1271       Handle(StepBasic_ProductDefinition) PD =
1272         Handle(StepBasic_ProductDefinition)::DownCast(enti);
1273       if (PD.IsNull()) continue;
1274       Handle(StepBasic_Product) Prod = (!PD->Formation().IsNull() ? PD->Formation()->OfProduct() : NULL);
1275       if (Prod.IsNull())
1276         name = new TCollection_HAsciiString;
1277       else if (!Prod->Name().IsNull() && Prod->Name()->UsefullLength() > 0)
1278         name = Prod->Name();
1279       else if (!Prod->Id().IsNull())
1280         name = Prod->Id();
1281       else
1282         name = new TCollection_HAsciiString;
1283       L = GetLabelFromPD(PD, STool, TP, PDFileMap, ShapeLabelMap);
1284       if (L.IsNull()) continue;
1285       TCollection_ExtendedString str = convertName (name->String());
1286       TDataStd_Name::Set(L, str);
1287     }
1288     // set a name to the document
1289     //TCollection_ExtendedString str = convertName (name->String());
1290     //TDataStd_Name::Set ( L, str );
1291   }
1292
1293   return Standard_True;
1294 }
1295
1296 //=======================================================================
1297 //function : GetLabelFromPD
1298 //purpose  : 
1299 //=======================================================================
1300
1301 static TDF_Label GetLabelFromPD(const Handle(StepBasic_ProductDefinition) &PD,
1302   const Handle(XCAFDoc_ShapeTool) &STool,
1303   const STEPConstruct_ValidationProps &Props,
1304   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1305   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1306 {
1307   TDF_Label L;
1308   if (PDFileMap.IsBound(PD)) {
1309     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find(PD);
1310     if (!EF.IsNull()) {
1311       L = EF->GetLabel();
1312       if (!L.IsNull()) return L;
1313     }
1314   }
1315   TopoDS_Shape S = Props.GetPropShape(PD);
1316   if (S.IsNull()) return L;
1317   if (ShapeLabelMap.IsBound(S))
1318     L = ShapeLabelMap.Find(S);
1319   if (L.IsNull())
1320     STool->Search(S, L, Standard_True, Standard_True, Standard_False);
1321   return L;
1322 }
1323
1324 //=======================================================================
1325 //function : ReadValProps
1326 //purpose  : 
1327 //=======================================================================
1328
1329 Standard_Boolean STEPCAFControl_Reader::ReadValProps(const Handle(XSControl_WorkSession) &WS,
1330   Handle(TDocStd_Document)& Doc,
1331   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1332   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1333 {
1334   // get starting data
1335   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
1336   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
1337   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool(Doc->Main());
1338   if (STool.IsNull()) return Standard_False;
1339
1340   // load props from the STEP model
1341   TColStd_SequenceOfTransient props;
1342   STEPConstruct_ValidationProps Props(WS);
1343   if (!Props.LoadProps(props)) {
1344 #ifdef OCCT_DEBUG
1345     std::cout << "Warning: no validation props found in the model" << std::endl;
1346 #endif
1347     return Standard_False;
1348   }
1349
1350   // interpret props one by one
1351   for (Standard_Integer i = 1; i <= props.Length(); i++) {
1352     Handle(StepRepr_PropertyDefinitionRepresentation) PDR =
1353       Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast(props.Value(i));
1354     if (PDR.IsNull()) continue;
1355
1356     TDF_Label L;
1357
1358     Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
1359     Interface_EntityIterator subs = Props.Graph().Shareds(PD);
1360     for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
1361       if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) {
1362         Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1363         if (PDS.IsNull()) continue;
1364         // find corresponding NAUO
1365         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
1366         Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
1367         for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
1368           if (subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)))
1369             NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
1370         }
1371         if (!NAUO.IsNull()) {
1372           L = FindInstance(NAUO, STool, WS, ShapeLabelMap);
1373           if (L.IsNull()) continue;
1374         }
1375         else {
1376           // find corresponding ProductDefinition:
1377           Handle(StepBasic_ProductDefinition) ProdDef;
1378           Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
1379           for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
1380             if (subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)))
1381               ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
1382           }
1383           if (ProdDef.IsNull()) continue;
1384           L = GetLabelFromPD(ProdDef, STool, Props, PDFileMap, ShapeLabelMap);
1385         }
1386       }
1387
1388       if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))) {
1389         Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
1390         if (SA.IsNull()) continue;
1391         // find ShapeRepresentation
1392         Handle(StepShape_ShapeRepresentation) SR;
1393         Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
1394         for (subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
1395           Handle(StepRepr_PropertyDefinition) PropD1 =
1396             Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
1397           if (PropD1.IsNull()) continue;
1398           Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
1399           for (subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
1400             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1401               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
1402             if (SDR.IsNull()) continue;
1403             SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1404           }
1405         }
1406         if (SR.IsNull()) continue;
1407         Handle(Transfer_Binder) binder;
1408         for (Standard_Integer ir = 1; ir <= SR->NbItems() && binder.IsNull(); ir++) {
1409           if (SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
1410             Handle(StepShape_SolidModel) SM =
1411               Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
1412             binder = TP->Find(SM);
1413           }
1414           else if (SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1415             Handle(StepShape_ShellBasedSurfaceModel) SBSM =
1416               Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
1417             binder = TP->Find(SBSM);
1418           }
1419           else if (SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1420             Handle(StepShape_GeometricSet) GS =
1421               Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
1422             binder = TP->Find(GS);
1423           }
1424         }
1425         if (binder.IsNull() || !binder->HasResult()) continue;
1426         TopoDS_Shape S;
1427         S = TransferBRep::ShapeResult(TP, binder);
1428         if (S.IsNull()) continue;
1429         if (ShapeLabelMap.IsBound(S))
1430           L = ShapeLabelMap.Find(S);
1431         if (L.IsNull())
1432           STool->Search(S, L, Standard_True, Standard_True, Standard_True);
1433       }
1434     }
1435
1436     if (L.IsNull()) continue;
1437
1438     // decode validation properties
1439     Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
1440     for (Standard_Integer j = 1; j <= rep->NbItems(); j++) {
1441       Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
1442       Standard_Boolean isArea;
1443       Standard_Real val;
1444       gp_Pnt pos;
1445       if (Props.GetPropReal(ent, val, isArea)) {
1446         if (isArea) XCAFDoc_Area::Set(L, val);
1447         else XCAFDoc_Volume::Set(L, val);
1448       }
1449       else if (Props.GetPropPnt(ent, rep->ContextOfItems(), pos)) {
1450         XCAFDoc_Centroid::Set(L, pos);
1451       }
1452     }
1453   }
1454   return Standard_True;
1455 }
1456
1457 //=======================================================================
1458 //function : ReadLayers
1459 //purpose  : 
1460 //=======================================================================
1461
1462 Standard_Boolean STEPCAFControl_Reader::ReadLayers(const Handle(XSControl_WorkSession) &WS,
1463   Handle(TDocStd_Document)& Doc) const
1464 {
1465   const Handle(Interface_InterfaceModel) &Model = WS->Model();
1466   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
1467   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
1468   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool(Doc->Main());
1469   if (STool.IsNull()) return Standard_False;
1470   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool(Doc->Main());
1471   if (LTool.IsNull()) return Standard_False;
1472
1473   Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
1474   Standard_Integer nb = Model->NbEntities();
1475   Handle(TCollection_HAsciiString) name;
1476
1477   for (Standard_Integer i = 1; i <= nb; i++) {
1478     Handle(Standard_Transient) enti = Model->Value(i);
1479     if (!enti->IsKind(tSVPLA)) continue;
1480     Handle(StepVisual_PresentationLayerAssignment) SVPLA =
1481       Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
1482     if (SVPLA->AssignedItems().IsNull())
1483       continue;
1484
1485     Handle(TCollection_HAsciiString) descr = SVPLA->Description();
1486     Handle(TCollection_HAsciiString) hName = SVPLA->Name();
1487     TCollection_ExtendedString aLayerName(hName->String());
1488
1489     // find a target shape and its label in the document
1490     for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++) {
1491       StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
1492       Handle(Transfer_Binder) binder = TP->Find(LI.Value());
1493       if (binder.IsNull() || !binder->HasResult()) continue;
1494
1495       TopoDS_Shape S = TransferBRep::ShapeResult(TP, binder);
1496       if (S.IsNull()) continue;
1497
1498       TDF_Label shL;
1499       if (!STool->Search(S, shL, Standard_True, Standard_True, Standard_True)) continue;
1500       LTool->SetLayer(shL, aLayerName);
1501     }
1502
1503     // check invisibility
1504     Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
1505     for (subs.Start(); subs.More(); subs.Next()) {
1506       if (!subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility))) continue;
1507 #ifdef OCCT_DEBUG
1508       std::cout << "\tLayer \"" << aLayerName << "\" is invisible" << std::endl;
1509 #endif
1510       //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
1511       TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
1512       TDataStd_UAttribute::Set (InvLayerLab, XCAFDoc::InvisibleGUID());
1513     }
1514   }
1515   return Standard_True;
1516 }
1517
1518 //=======================================================================
1519 //function : ReadSHUOs
1520 //purpose  : 
1521 //=======================================================================
1522
1523 static Standard_Boolean findNextSHUOlevel(const Handle(XSControl_WorkSession) &WS,
1524   const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1525   const Handle(XCAFDoc_ShapeTool)& STool,
1526   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1527   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1528   TDF_LabelSequence& aLabels)
1529 {
1530   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1531   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1532   for (subs.Start(); subs.More(); subs.Next()) {
1533     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1534       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1535       break;
1536     }
1537   }
1538   if (subSHUO.IsNull())
1539     return Standard_False;
1540
1541   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = subSHUO->NextUsage();
1542   if (NUNAUO.IsNull())
1543     return Standard_False;
1544   //   Handle(Interface_InterfaceModel) Model = WS->Model();
1545   //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1546   //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1547   //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1548   //   if ( binder.IsNull() || ! binder->HasResult() )
1549   //     return Standard_False;
1550   //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1551     // get label of NAUO next level
1552   TDF_Label NULab;
1553   STEPConstruct_Tool Tool(WS);
1554   NULab = STEPCAFControl_Reader::FindInstance(NUNAUO, STool, Tool, ShapeLabelMap);
1555   //   STool->Search(NUSh, NUlab);
1556   if (NULab.IsNull())
1557     return Standard_False;
1558   aLabels.Append(NULab);
1559   // and check by recurse.
1560   findNextSHUOlevel(WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels);
1561   return Standard_True;
1562 }
1563
1564
1565 //=======================================================================
1566 //function : setSHUOintoDoc
1567 //purpose  : auxilary
1568 //=======================================================================
1569 static TDF_Label setSHUOintoDoc(const Handle(XSControl_WorkSession) &WS,
1570   const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1571   const Handle(XCAFDoc_ShapeTool)& STool,
1572   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1573   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1574 {
1575   TDF_Label aMainLabel;
1576   // get upper usage NAUO from SHUO.
1577   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1578     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1579   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = SHUO->NextUsage();
1580   if (UUNAUO.IsNull() || NUNAUO.IsNull()) {
1581 #ifdef OCCT_DEBUG
1582     std::cout << "Warning: " << __FILE__ << ": Upper_usage or Next_usage of styled SHUO is null. Skip it" << std::endl;
1583 #endif
1584     return aMainLabel;
1585   }
1586   //   Handle(Interface_InterfaceModel) Model = WS->Model();
1587   //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1588   //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1589   //   TopoDS_Shape UUSh, NUSh;
1590   //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1591   //   if ( binder.IsNull() || ! binder->HasResult() )
1592   //     return aMainLabel;
1593   //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1594   //   binder = TP->Find(NUNAUO);
1595   //   if ( binder.IsNull() || ! binder->HasResult() )
1596   //     return aMainLabel;
1597   //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1598
1599     // get first labels for first SHUO attribute
1600   TDF_Label UULab, NULab;
1601   STEPConstruct_Tool Tool(WS);
1602   UULab = STEPCAFControl_Reader::FindInstance(UUNAUO, STool, Tool, ShapeLabelMap);
1603   NULab = STEPCAFControl_Reader::FindInstance(NUNAUO, STool, Tool, ShapeLabelMap);
1604
1605   //   STool->Search(UUSh, UULab);
1606   //   STool->Search(NUSh, NULab);
1607   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1608   //create sequence fo labels to set SHUO structure into the document
1609   TDF_LabelSequence ShuoLabels;
1610   ShuoLabels.Append(UULab);
1611   ShuoLabels.Append(NULab);
1612   // add all other labels of sub SHUO entities
1613   findNextSHUOlevel(WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels);
1614   // last accord for SHUO
1615   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1616   if (STool->SetSHUO(ShuoLabels, anSHUOAttr))
1617     aMainLabel = anSHUOAttr->Label();
1618
1619   return aMainLabel;
1620 }
1621
1622
1623 //=======================================================================
1624 //function : ReadSHUOs
1625 //purpose  : 
1626 //=======================================================================
1627
1628 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs(const Handle(XSControl_WorkSession) &WS,
1629   Handle(TDocStd_Document)& Doc,
1630   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1631   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1632 {
1633   // the big part code duplication from ReadColors.
1634   // It is possible to share this code functionality, just to decide how ???
1635   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool(Doc->Main());
1636   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1637
1638   STEPConstruct_Styles Styles(WS);
1639   if (!Styles.LoadStyles()) {
1640 #ifdef OCCT_DEBUG
1641     std::cout << "Warning: no styles are found in the model" << std::endl;
1642 #endif
1643     return Standard_False;
1644   }
1645   // searching for invisible items in the model
1646   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1647   Styles.LoadInvisStyles(aHSeqOfInvisStyle);
1648   // parse and search for color attributes
1649   Standard_Integer nb = Styles.NbStyles();
1650   for (Standard_Integer i = 1; i <= nb; i++) {
1651     Handle(StepVisual_StyledItem) style = Styles.Style(i);
1652     if (style.IsNull()) continue;
1653
1654     Standard_Boolean IsVisible = Standard_True;
1655     // check the visibility of styled item.
1656     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++) {
1657       if (style != aHSeqOfInvisStyle->Value(si))
1658         continue;
1659       // found that current style is invisible.
1660 #ifdef OCCT_DEBUG
1661       std::cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << std::endl;
1662 #endif
1663       IsVisible = Standard_False;
1664       break;
1665     }
1666
1667     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol, RenderCol;
1668     Standard_Real RenderTransp;
1669     // check if it is component style
1670     Standard_Boolean IsComponent = Standard_False;
1671     if (!Styles.GetColors(style, SurfCol, BoundCol, CurveCol, RenderCol, RenderTransp, IsComponent) && IsVisible)
1672       continue;
1673     if (!IsComponent)
1674       continue;
1675     Handle(StepShape_ShapeRepresentation) aSR;
1676     findStyledSR(style, aSR);
1677     // search for SR along model
1678     if (aSR.IsNull())
1679       continue;
1680     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(aSR);
1681     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1682     for (subs.Start(); subs.More(); subs.Next()) {
1683       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1684       if (aSDR.IsNull())
1685         continue;
1686       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1687       Handle(StepRepr_ProductDefinitionShape) PDS =
1688         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1689       if (PDS.IsNull())
1690         continue;
1691       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1692       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1693         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1694       if (SHUO.IsNull())
1695         continue;
1696
1697       // set the SHUO structure to the document
1698       TDF_Label aLabelForStyle = setSHUOintoDoc(WS, SHUO, STool, PDFileMap, ShapeLabelMap);
1699       if (aLabelForStyle.IsNull()) {
1700 #ifdef OCCT_DEBUG
1701         std::cout << "Warning: " << __FILE__ << ": coudnot create SHUO structure in the document" << std::endl;
1702 #endif
1703         continue;
1704       }
1705       // now set the style to the SHUO main label.
1706       if (!SurfCol.IsNull() || !RenderCol.IsNull()) {
1707         Quantity_Color col;
1708         Quantity_ColorRGBA colRGBA;
1709         if (!SurfCol.IsNull()) {
1710             Styles.DecodeColor(SurfCol, col);
1711             colRGBA = Quantity_ColorRGBA(col);
1712         }
1713         if (!RenderCol.IsNull()) {
1714             Styles.DecodeColor(RenderCol, col);
1715             colRGBA = Quantity_ColorRGBA(col, static_cast<float>(1.0 - RenderTransp));
1716         }
1717         CTool->SetColor(aLabelForStyle, colRGBA, XCAFDoc_ColorSurf);
1718       }
1719       if (!BoundCol.IsNull()) {
1720         Quantity_Color col;
1721         Styles.DecodeColor(BoundCol, col);
1722         CTool->SetColor(aLabelForStyle, col, XCAFDoc_ColorCurv);
1723       }
1724       if (!CurveCol.IsNull()) {
1725         Quantity_Color col;
1726         Styles.DecodeColor(CurveCol, col);
1727         CTool->SetColor(aLabelForStyle, col, XCAFDoc_ColorCurv);
1728       }
1729       if (!IsVisible)
1730         // sets the invisibility for shape.
1731         CTool->SetVisibility(aLabelForStyle, Standard_False);
1732
1733     } // end search SHUO by SDR
1734   } // end iterates on styles
1735
1736   return Standard_True;
1737 }
1738
1739 //=======================================================================
1740 //function : GetMassConversionFactor
1741 //purpose  : 
1742 //=======================================================================
1743 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1744   Standard_Real& afact)
1745 {
1746   afact = 1.;
1747   if (!NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit))) return Standard_False;
1748   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1749     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1750   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1751   afact = MWUCBU->ValueComponent();
1752   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1753   if (anUnit2.CaseNum(anUnit2.Value()) == 1) {
1754     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1755     if (NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1756       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1757       if (SU->Name() == StepBasic_sunGram) {
1758         if (SU->HasPrefix())
1759           afact *= STEPConstruct_UnitContext::ConvertSiPrefix(SU->Prefix());
1760       }
1761     }
1762   }
1763   return Standard_True;
1764 }
1765
1766 //=======================================================================
1767 //function : readPMIPresentation
1768 //purpose  : read polyline or tessellated presentation for 
1769 // (Annotation_Curve_Occurrence or Draughting_Callout)
1770 //=======================================================================
1771 Standard_Boolean readPMIPresentation(const Handle(Standard_Transient)& thePresentEntity,
1772   const Handle(XSControl_TransferReader)& theTR,
1773   const Standard_Real theFact,
1774   TopoDS_Shape& thePresentation,
1775   Handle(TCollection_HAsciiString)& thePresentName,
1776   Bnd_Box& theBox)
1777 {
1778   if (thePresentEntity.IsNull())
1779     return Standard_False;
1780   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1781   Handle(StepVisual_AnnotationOccurrence) anAO;
1782   NCollection_Vector<Handle(StepVisual_StyledItem)> anAnnotations;
1783   if (thePresentEntity->IsKind(STANDARD_TYPE(StepVisual_AnnotationOccurrence)))
1784   {
1785     anAO = Handle(StepVisual_AnnotationOccurrence)::DownCast(thePresentEntity);
1786     if (!anAO.IsNull()) {
1787       thePresentName = anAO->Name();
1788       anAnnotations.Append(anAO);
1789     }
1790   }
1791   else if (thePresentEntity->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout)))
1792   {
1793     Handle(StepVisual_DraughtingCallout) aDCallout =
1794       Handle(StepVisual_DraughtingCallout)::DownCast(thePresentEntity);
1795     thePresentName = aDCallout->Name();
1796     for (Standard_Integer i = 1; i <= aDCallout->NbContents() && anAO.IsNull(); i++) {
1797       anAO = Handle(StepVisual_AnnotationOccurrence)::DownCast(aDCallout->ContentsValue(i).Value());
1798       if (!anAO.IsNull())
1799       {
1800         anAnnotations.Append(anAO);
1801         continue;
1802       }
1803       Handle(StepVisual_TessellatedAnnotationOccurrence) aTesselation =
1804         aDCallout->ContentsValue(i).TessellatedAnnotationOccurrence();
1805       if (!aTesselation.IsNull())
1806         anAnnotations.Append(aTesselation);
1807     }
1808   }
1809
1810   if (!anAnnotations.Length())
1811     return Standard_False;
1812
1813
1814   BRep_Builder aB;
1815   TopoDS_Compound aResAnnotation;
1816   aB.MakeCompound(aResAnnotation);
1817
1818   Standard_Integer i = 0;
1819   Bnd_Box aBox;
1820   Standard_Integer nbShapes = 0;
1821   for (; i < anAnnotations.Length(); i++)
1822   {
1823     Handle(StepVisual_StyledItem) anItem = anAnnotations(i);
1824     anAO = Handle(StepVisual_AnnotationOccurrence)::DownCast(anItem);
1825     TopoDS_Shape anAnnotationShape;
1826     if (!anAO.IsNull())
1827     {
1828       Handle(StepRepr_RepresentationItem) aCurveItem = anAO->Item();
1829       anAnnotationShape = STEPConstruct::FindShape(aTP, aCurveItem);
1830       if (anAnnotationShape.IsNull())
1831       {
1832         Handle(Transfer_Binder) binder = theTR->Actor()->Transfer(aCurveItem, aTP);
1833         if (!binder.IsNull() && binder->HasResult()) {
1834           anAnnotationShape = TransferBRep::ShapeResult(aTP, binder);
1835         }
1836       }
1837     }
1838     //case of tessellated entities
1839     else
1840     {
1841       Handle(StepRepr_RepresentationItem) aTessItem = anItem->Item();
1842       if (aTessItem.IsNull())
1843         continue;
1844       Handle(StepVisual_TessellatedGeometricSet) aTessSet = Handle(StepVisual_TessellatedGeometricSet)::DownCast(aTessItem);
1845       if (aTessSet.IsNull())
1846         continue;
1847       NCollection_Handle<StepVisual_Array1OfTessellatedItem> aListItems = aTessSet->Items();
1848       Standard_Integer nb = aListItems.IsNull() ? 0 : aListItems->Length();
1849       Handle(StepVisual_TessellatedCurveSet) aTessCurve;
1850       for (Standard_Integer n = 1; n <= nb && aTessCurve.IsNull(); n++)
1851       {
1852         aTessCurve = Handle(StepVisual_TessellatedCurveSet)::DownCast(aListItems->Value(n));
1853       }
1854       if (aTessCurve.IsNull())
1855         continue;
1856       Handle(StepVisual_CoordinatesList) aCoordList = aTessCurve->CoordList();
1857       if (aCoordList.IsNull())
1858         continue;
1859       Handle(TColgp_HArray1OfXYZ)  aPoints = aCoordList->Points();
1860
1861       if (aPoints.IsNull() || aPoints->Length() == 0)
1862         continue;
1863       NCollection_Handle<StepVisual_VectorOfHSequenceOfInteger> aCurves = aTessCurve->Curves();
1864       Standard_Integer aNbC = (aCurves.IsNull() ? 0 : aCurves->Length());
1865       TopoDS_Compound aComp;
1866       aB.MakeCompound(aComp);
1867
1868       Standard_Integer k = 0;
1869       for (; k < aNbC; k++)
1870       {
1871         Handle(TColStd_HSequenceOfInteger) anIndexes = aCurves->Value(k);
1872         TopoDS_Wire aCurW;
1873         aB.MakeWire(aCurW);
1874
1875         for (Standard_Integer n = 1; n < anIndexes->Length(); n++)
1876         {
1877           Standard_Integer ind = anIndexes->Value(n);
1878           Standard_Integer indnext = anIndexes->Value(n + 1);
1879           if (ind > aPoints->Length() || indnext > aPoints->Length())
1880             continue;
1881           gp_Pnt aP1(aPoints->Value(ind) * theFact);
1882           gp_Pnt aP2(aPoints->Value(indnext) * theFact);
1883           BRepBuilderAPI_MakeEdge aMaker(aP1, aP2);
1884           if (aMaker.IsDone())
1885           {
1886             TopoDS_Edge aCurE = aMaker.Edge();
1887             aB.Add(aCurW, aCurE);
1888           }
1889         }
1890         aB.Add(aComp, aCurW);
1891       }
1892       anAnnotationShape = aComp;
1893     }
1894     if (!anAnnotationShape.IsNull())
1895     {
1896       nbShapes++;
1897       aB.Add(aResAnnotation, anAnnotationShape);
1898       if (i == anAnnotations.Length() - 1)
1899         BRepBndLib::AddClose(anAnnotationShape, aBox);
1900     }
1901   }
1902
1903   thePresentation = aResAnnotation;
1904   theBox = aBox;
1905   return (nbShapes > 0);
1906 }
1907
1908 //=======================================================================
1909 //function : readAnnotationPlane
1910 //purpose  : read annotation plane
1911 //=======================================================================
1912 Standard_Boolean readAnnotationPlane(const Handle(StepVisual_AnnotationPlane) theAnnotationPlane,
1913   gp_Ax2& thePlane)
1914 {
1915   if (theAnnotationPlane.IsNull())
1916     return Standard_False;
1917   Handle(StepRepr_RepresentationItem) aPlaneItem = theAnnotationPlane->Item();
1918   if (aPlaneItem.IsNull())
1919     return Standard_False;
1920   Handle(StepGeom_Axis2Placement3d) aA2P3D;
1921   //retrieve axes from AnnotationPlane
1922   if (aPlaneItem->IsKind(STANDARD_TYPE(StepGeom_Plane))) {
1923     Handle(StepGeom_Plane) aPlane = Handle(StepGeom_Plane)::DownCast(aPlaneItem);
1924     aA2P3D = aPlane->Position();
1925   }
1926   else if (aPlaneItem->IsKind(STANDARD_TYPE(StepVisual_PlanarBox))) {
1927     Handle(StepVisual_PlanarBox) aBox = Handle(StepVisual_PlanarBox)::DownCast(aPlaneItem);
1928     aA2P3D = aBox->Placement().Axis2Placement3d();
1929   }
1930   if (aA2P3D.IsNull())
1931     return Standard_False;
1932
1933   Handle(Geom_Axis2Placement) anAxis = StepToGeom::MakeAxis2Placement(aA2P3D);
1934   thePlane = anAxis->Ax2();
1935   return Standard_True;
1936 }
1937
1938 //=======================================================================
1939 //function : readAnnotation
1940 //purpose  : read annotation plane and position for given GDT
1941 // (Dimension, Geometric_Tolerance, Datum_Feature or Placed_Datum_Target_Feature)
1942 //=======================================================================
1943 void readAnnotation(const Handle(XSControl_TransferReader)& theTR,
1944   const Handle(Standard_Transient)& theGDT,
1945   const Handle(Standard_Transient)& theDimObject)
1946 {
1947   if (theGDT.IsNull() || theDimObject.IsNull())
1948     return;
1949   Handle(TCollection_HAsciiString) aPresentName;
1950   TopoDS_Compound aResAnnotation;
1951   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1952   const Interface_Graph& aGraph = aTP->Graph();
1953   // find the proper DraughtingModelItemAssociation
1954   Interface_EntityIterator subs = aGraph.Sharings(theGDT);
1955   Handle(StepAP242_DraughtingModelItemAssociation) aDMIA;
1956   for (subs.Start(); subs.More() && aDMIA.IsNull(); subs.Next()) {
1957     if (!subs.Value()->IsKind(STANDARD_TYPE(StepAP242_DraughtingModelItemAssociation)))
1958       continue;
1959     aDMIA = Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(subs.Value());
1960     Handle(TCollection_HAsciiString) aName = aDMIA->Name();
1961     aName->LowerCase();
1962     if (!aName->Search(new TCollection_HAsciiString("pmi representation to presentation link"))) {
1963       aDMIA = NULL;
1964     }
1965   }
1966   if (aDMIA.IsNull() || aDMIA->NbIdentifiedItem() == 0)
1967     return;
1968
1969   // calculate units
1970   Handle(StepVisual_DraughtingModel) aDModel =
1971     Handle(StepVisual_DraughtingModel)::DownCast(aDMIA->UsedRepresentation());
1972   XSAlgo::AlgoContainer()->PrepareForTransfer();
1973   STEPControl_ActorRead anActor;
1974   anActor.PrepareUnits(aDModel, aTP);
1975   Standard_Real aFact = UnitsMethods::LengthFactor();
1976
1977   // retrieve AnnotationPlane
1978   Handle(StepRepr_RepresentationItem) aDMIAE = aDMIA->IdentifiedItemValue(1);
1979   if (aDMIAE.IsNull())
1980     return;
1981   gp_Ax2 aPlaneAxes;
1982   subs = aGraph.Sharings(aDMIAE);
1983   Handle(StepVisual_AnnotationPlane) anAnPlane;
1984   for (subs.Start(); subs.More() && anAnPlane.IsNull(); subs.Next()) {
1985     anAnPlane = Handle(StepVisual_AnnotationPlane)::DownCast(subs.Value());
1986   }
1987   Standard_Boolean isHasPlane = readAnnotationPlane(anAnPlane, aPlaneAxes);
1988
1989   // set plane axes to XCAF
1990   if (isHasPlane) {
1991     if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1992       Handle(XCAFDimTolObjects_DimensionObject) anObj =
1993         Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1994       Handle(TColgp_HArray1OfPnt) aPnts = new TColgp_HArray1OfPnt(1, 1);
1995       anObj->SetPlane(aPlaneAxes);
1996     }
1997     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1998       Handle(XCAFDimTolObjects_DatumObject) anObj =
1999         Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
2000       anObj->SetPlane(aPlaneAxes);
2001     }
2002     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
2003       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
2004         Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
2005       anObj->SetPlane(aPlaneAxes);
2006     }
2007   }
2008
2009   // Retrieve presentation
2010   Bnd_Box aBox;
2011   if (!readPMIPresentation(aDMIAE, theTR, aFact, aResAnnotation, aPresentName, aBox))
2012     return;
2013   gp_Pnt aPtext(0., 0., 0.);
2014   // if Annotation plane location inside bounding box set it to text position
2015   // else set the center of bounding box to text position 0027372
2016   if (!aBox.IsVoid())
2017   {
2018     Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
2019     aBox.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2020     if (isHasPlane && !aBox.IsOut(aPlaneAxes.Location())) {
2021       aPtext = aPlaneAxes.Location();
2022     }
2023     else {
2024       aPtext = gp_Pnt((aXmin + aXmax) * 0.5, (aYmin + aYmax) * 0.5, (aZmin + aZmax) * 0.5);
2025     }
2026   }
2027   else {
2028     aPtext = aPlaneAxes.Location();
2029   }
2030
2031   // set point to XCAF
2032   if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
2033     Handle(XCAFDimTolObjects_DimensionObject) anObj =
2034       Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
2035     anObj->SetPointTextAttach(aPtext);
2036     anObj->SetPresentation(aResAnnotation, aPresentName);
2037   }
2038   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
2039     Handle(XCAFDimTolObjects_DatumObject) anObj =
2040       Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
2041     anObj->SetPointTextAttach(aPtext);
2042     anObj->SetPresentation(aResAnnotation, aPresentName);
2043   }
2044   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
2045     Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
2046       Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
2047     anObj->SetPointTextAttach(aPtext);
2048     anObj->SetPresentation(aResAnnotation, aPresentName);
2049   }
2050   return;
2051 }
2052
2053 //=======================================================================
2054 //function : readConnectionPoints
2055 //purpose  : read connection points for given dimension
2056 //=======================================================================
2057 void readConnectionPoints(const Handle(XSControl_TransferReader)& theTR,
2058   const Handle(Standard_Transient) theGDT,
2059   const Handle(XCAFDimTolObjects_DimensionObject)& theDimObject)
2060 {
2061   if (theGDT.IsNull() || theDimObject.IsNull())
2062     return;
2063   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
2064   const Interface_Graph& aGraph = aTP->Graph();
2065
2066   
2067   Standard_Real aFact = 1.;
2068
2069   Handle(StepShape_ShapeDimensionRepresentation) aSDR = NULL;
2070   for (Interface_EntityIterator anIt = aGraph.Sharings(theGDT); aSDR.IsNull() && anIt.More(); anIt.Next()) {
2071     Handle(Standard_Transient) anEnt = anIt.Value();
2072     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR =
2073       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anEnt);
2074     if (!aDCR.IsNull())
2075       aSDR = !aDCR.IsNull() ? aDCR->Representation() : Handle(StepShape_ShapeDimensionRepresentation)::DownCast(anEnt);
2076   }
2077   if (!aSDR.IsNull())
2078   {
2079     XSAlgo::AlgoContainer()->PrepareForTransfer();
2080     STEPControl_ActorRead anActor;
2081     anActor.PrepareUnits(aSDR, aTP);
2082     aFact = UnitsMethods::LengthFactor();
2083   }
2084   
2085   if (theGDT->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2086     // retrieve derived geometry
2087     Handle(StepShape_DimensionalSize) aDim = Handle(StepShape_DimensionalSize)::DownCast(theGDT);
2088     Handle(StepRepr_DerivedShapeAspect) aDSA = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->AppliesTo());
2089     if (aDSA.IsNull())
2090       return;
2091     Handle(StepAP242_GeometricItemSpecificUsage) aGISU = NULL;
2092     for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA); aGISU.IsNull() && anIt.More(); anIt.Next()) {
2093       aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2094     }
2095     if (aGISU.IsNull() || aGISU->NbIdentifiedItem() == 0)
2096       return;
2097     Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU->IdentifiedItem()->Value(1));
2098     if (aPoint.IsNull()) {
2099       // try Axis2Placement3d.location instead of CartesianPoint
2100       Handle(StepGeom_Axis2Placement3d) anA2P3D =
2101         Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU->IdentifiedItem()->Value(1));
2102       if (anA2P3D.IsNull())
2103         return;
2104       aPoint = anA2P3D->Location();
2105     }
2106
2107     // set connection point to object
2108     gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2109     theDimObject->SetPoint(aPnt);
2110   }
2111   else if (theGDT->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2112     // retrieve derived geometry
2113     Handle(StepShape_DimensionalLocation) aDim = Handle(StepShape_DimensionalLocation)::DownCast(theGDT);
2114     Handle(StepRepr_DerivedShapeAspect) aDSA1 = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->RelatingShapeAspect());
2115     Handle(StepRepr_DerivedShapeAspect) aDSA2 = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->RelatedShapeAspect());
2116     if (aDSA1.IsNull() && aDSA2.IsNull())
2117       return;
2118     Handle(StepAP242_GeometricItemSpecificUsage) aGISU1 = NULL;
2119     Handle(StepAP242_GeometricItemSpecificUsage) aGISU2 = NULL;
2120     if (!aDSA1.IsNull()) {
2121       for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA1); aGISU1.IsNull() && anIt.More(); anIt.Next()) {
2122         aGISU1 = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2123       }
2124     }
2125     if (!aDSA2.IsNull()) {
2126       for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA2); aGISU2.IsNull() && anIt.More(); anIt.Next()) {
2127         aGISU2 = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2128       }
2129     }
2130     // first point
2131     if (!aGISU1.IsNull() && aGISU1->NbIdentifiedItem() > 0) {
2132       Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU1->IdentifiedItem()->Value(1));
2133       if (aPoint.IsNull()) {
2134         // try Axis2Placement3d.location instead of CartesianPoint
2135         Handle(StepGeom_Axis2Placement3d) anA2P3D =
2136           Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU1->IdentifiedItem()->Value(1));
2137         if (!anA2P3D.IsNull())
2138           aPoint = anA2P3D->Location();
2139       }
2140       if (!aPoint.IsNull()) {
2141         // set connection point to object
2142         gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2143         theDimObject->SetPoint(aPnt);
2144       }
2145     }
2146     // second point
2147     if (!aGISU2.IsNull() && aGISU2->NbIdentifiedItem() > 0) {
2148       Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU2->IdentifiedItem()->Value(1));
2149       if (aPoint.IsNull()) {
2150         // try Axis2Placement3d.location instead of CartesianPoint
2151         Handle(StepGeom_Axis2Placement3d) anA2P3D =
2152           Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU2->IdentifiedItem()->Value(1));
2153         if (!anA2P3D.IsNull())
2154           aPoint = anA2P3D->Location();
2155       }
2156       if (!aPoint.IsNull()) {
2157         // set connection point to object
2158         gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2159         theDimObject->SetPoint2(aPnt);
2160       }
2161     }
2162   }
2163 }
2164
2165 //=======================================================================
2166 //function : ReadDatums
2167 //purpose  : auxilary
2168 //=======================================================================
2169 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
2170   const Handle(XCAFDoc_DimTolTool) &DGTTool,
2171   const Interface_Graph &graph,
2172   const Handle(Transfer_TransientProcess) &TP,
2173   const TDF_Label TolerL,
2174   const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
2175 {
2176   if (GTWDR.IsNull()) return Standard_False;
2177   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
2178   if (HADR.IsNull()) return Standard_False;
2179   for (Standard_Integer idr = 1; idr <= HADR->Length(); idr++) {
2180     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
2181     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
2182     if (aDatum.IsNull()) continue;
2183     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
2184     for (subs4.Start(); subs4.More(); subs4.Next()) {
2185       Handle(StepRepr_ShapeAspectRelationship) SAR =
2186         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
2187       if (SAR.IsNull()) continue;
2188       Handle(StepDimTol_DatumFeature) DF =
2189         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
2190       if (DF.IsNull()) continue;
2191       Interface_EntityIterator subs5 = graph.Sharings(DF);
2192       Handle(StepRepr_PropertyDefinition) PropDef;
2193       for (subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
2194         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
2195       }
2196       if (PropDef.IsNull()) continue;
2197       Handle(StepShape_AdvancedFace) AF;
2198       subs5 = graph.Sharings(PropDef);
2199       for (subs5.Start(); subs5.More(); subs5.Next()) {
2200         Handle(StepShape_ShapeDefinitionRepresentation) SDR =
2201           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
2202         if (!SDR.IsNull()) {
2203           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2204           if (!Repr.IsNull() && Repr->NbItems() > 0) {
2205             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
2206             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2207           }
2208         }
2209       }
2210       if (AF.IsNull()) return Standard_False;
2211       Standard_Integer index = TP->MapIndex(AF);
2212       TopoDS_Shape aSh;
2213       if (index > 0) {
2214         Handle(Transfer_Binder) binder = TP->MapItem(index);
2215         aSh = TransferBRep::ShapeResult(binder);
2216       }
2217       if (aSh.IsNull()) continue;
2218       TDF_Label shL;
2219       if (!STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True)) continue;
2220       DGTTool->SetDatum(shL, TolerL, PropDef->Name(), PropDef->Description(), aDatum->Identification());
2221     }
2222   }
2223   return Standard_True;
2224 }
2225
2226 //=======================================================================
2227 //function : FindShapeIndexForDGT
2228 //purpose  : auxiliary find shape index in map og imported shapes
2229 //=======================================================================
2230 static Standard_Integer FindShapeIndexForDGT(const Handle(Standard_Transient)& theEnt,
2231   const Handle(XSControl_WorkSession)& theWS)
2232 {
2233   const Handle(Transfer_TransientProcess) &aTP = theWS->TransferReader()->TransientProcess();
2234   // try to find index of given entity
2235   Standard_Integer anIndex = aTP->MapIndex(theEnt);
2236   if (anIndex > 0)
2237     return anIndex;
2238   // if theEnt is a geometry item try to find its topological item
2239   const Interface_Graph& aGraph = aTP->Graph();
2240   Interface_EntityIterator anIter = aGraph.Sharings(theEnt);
2241   for (anIter.Start(); anIter.More(); anIter.Next()) {
2242     if (anIter.Value()->IsKind(STANDARD_TYPE(StepShape_TopologicalRepresentationItem)))
2243     {
2244       anIndex = aTP->MapIndex(anIter.Value());
2245       if (anIndex > 0)
2246         return anIndex;
2247     }
2248   }
2249   return 0;
2250 }
2251
2252 //=======================================================================
2253 //function : collectShapeAspect
2254 //purpose  : 
2255 //=======================================================================
2256 static void collectShapeAspect(const Handle(StepRepr_ShapeAspect)& theSA,
2257   const Handle(XSControl_WorkSession)& theWS,
2258   NCollection_Sequence<Handle(StepRepr_ShapeAspect)>& theSAs)
2259 {
2260   if (theSA.IsNull())
2261     return;
2262   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2263   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2264   const Interface_Graph& aGraph = aTP->Graph();
2265   // Retrieve Shape_Aspect, connected to Representation_Item from Derived_Shape_Aspect
2266   if (theSA->IsKind(STANDARD_TYPE(StepRepr_DerivedShapeAspect))) {
2267     Interface_EntityIterator anIter = aGraph.Sharings(theSA);
2268     Handle(StepRepr_ShapeAspectDerivingRelationship) aSADR = NULL;
2269     for (; aSADR.IsNull() && anIter.More(); anIter.Next()) {
2270       aSADR = Handle(StepRepr_ShapeAspectDerivingRelationship)::DownCast(anIter.Value());
2271     }
2272     if (!aSADR.IsNull())
2273       collectShapeAspect(aSADR->RelatedShapeAspect(), theWS, theSAs);
2274   }
2275   else if (theSA->IsKind(STANDARD_TYPE(StepDimTol_DatumFeature)) ||
2276     theSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget))) {
2277     theSAs.Append(theSA);
2278     return;
2279   }
2280   else {
2281     // Find all children Shape_Aspect
2282     Standard_Boolean isSimple = Standard_True;
2283     Interface_EntityIterator anIter = aGraph.Sharings(theSA);
2284     for (; anIter.More(); anIter.Next()) {
2285       if (anIter.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship)) &&
2286         !anIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2287         Handle(StepRepr_ShapeAspectRelationship) aSAR =
2288           Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIter.Value());
2289         if (aSAR->RelatingShapeAspect() == theSA && !aSAR->RelatedShapeAspect().IsNull()
2290           && !aSAR->RelatedShapeAspect()->IsKind(STANDARD_TYPE(StepDimTol_Datum))) {
2291           collectShapeAspect(aSAR->RelatedShapeAspect(), theWS, theSAs);
2292           isSimple = Standard_False;
2293         }
2294       }
2295     }
2296     // If not Composite_Shape_Aspect (or subtype) append to sequence.
2297     if (isSimple)
2298       theSAs.Append(theSA);
2299   }
2300 }
2301
2302 //=======================================================================
2303 //function : getShapeLabel
2304 //purpose  : 
2305 //=======================================================================
2306
2307 static TDF_Label getShapeLabel(const Handle(StepRepr_RepresentationItem)& theItem,
2308   const Handle(XSControl_WorkSession)& theWS,
2309   const Handle(XCAFDoc_ShapeTool)& theShapeTool)
2310 {
2311   TDF_Label aShapeL;
2312   const Handle(Transfer_TransientProcess) &aTP = theWS->TransferReader()->TransientProcess();
2313   Standard_Integer index = FindShapeIndexForDGT(theItem, theWS);
2314   TopoDS_Shape aShape;
2315   if (index > 0) {
2316     Handle(Transfer_Binder) aBinder = aTP->MapItem(index);
2317     aShape = TransferBRep::ShapeResult(aBinder);
2318   }
2319   if (aShape.IsNull())
2320     return aShapeL;
2321   theShapeTool->Search(aShape, aShapeL, Standard_True, Standard_True, Standard_True);
2322   return aShapeL;
2323 }
2324
2325 //=======================================================================
2326 //function : setDatumToXCAF
2327 //purpose  : 
2328 //=======================================================================
2329
2330 Standard_Boolean STEPCAFControl_Reader::setDatumToXCAF(const Handle(StepDimTol_Datum)& theDat,
2331   const TDF_Label theGDTL,
2332   const Standard_Integer thePositionCounter,
2333   const XCAFDimTolObjects_DatumModifiersSequence& theXCAFModifiers,
2334   const XCAFDimTolObjects_DatumModifWithValue theXCAFModifWithVal,
2335   const Standard_Real theModifValue,
2336   const Handle(TDocStd_Document)& theDoc,
2337   const Handle(XSControl_WorkSession)& theWS)
2338 {
2339   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
2340   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
2341   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2342   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2343   const Interface_Graph& aGraph = aTP->Graph();
2344   Handle(XCAFDoc_Datum) aDat;
2345   TDF_LabelSequence aShapeLabels;
2346   Handle(XCAFDimTolObjects_DatumObject) aDatObj = new XCAFDimTolObjects_DatumObject();
2347
2348   // Collect all links to shapes
2349   NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2350   Interface_EntityIterator anIterD = aGraph.Sharings(theDat);
2351   for (anIterD.Start(); anIterD.More(); anIterD.Next()) {
2352     Handle(StepRepr_ShapeAspectRelationship) aSAR = Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterD.Value());
2353     if (aSAR.IsNull() || aSAR->RelatingShapeAspect().IsNull())
2354       continue;
2355     collectShapeAspect(aSAR->RelatingShapeAspect(), theWS, aSAs);
2356     Handle(StepDimTol_DatumFeature) aDF = Handle(StepDimTol_DatumFeature)::DownCast(aSAR->RelatingShapeAspect());
2357     if (!aSAR->RelatingShapeAspect()->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)))
2358       readAnnotation(aTR, aSAR->RelatingShapeAspect(), aDatObj);
2359   }
2360
2361   // Collect shape labels
2362   for (Standard_Integer i = 1; i <= aSAs.Length(); i++) {
2363     Handle(StepRepr_ShapeAspect) aSA = aSAs.Value(i);
2364     if (aSA.IsNull())
2365       continue;
2366     // Skip datum targets
2367     if (aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)))
2368       continue;
2369
2370     // Process all connected GISU
2371     Interface_EntityIterator anIter = aGraph.Sharings(aSA);
2372     for (; anIter.More(); anIter.Next()) {
2373       Handle(StepAP242_GeometricItemSpecificUsage) aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIter.Value());
2374       if (aGISU.IsNull())
2375         continue;
2376       for (Standard_Integer j = 1; j <= aGISU->NbIdentifiedItem(); j++) {
2377         TDF_Label aShapeL = getShapeLabel(aGISU->IdentifiedItemValue(j), theWS, aSTool);
2378         if (!aShapeL.IsNull())
2379           aShapeLabels.Append(aShapeL);
2380       }
2381     }
2382   }
2383
2384   // Process datum targets and create objects for them
2385   Standard_Boolean isExistDatumTarget = Standard_False;
2386   for (Standard_Integer i = 1; i <= aSAs.Length(); i++) {
2387     Handle(StepDimTol_PlacedDatumTargetFeature) aDT = Handle(StepDimTol_PlacedDatumTargetFeature)::DownCast(aSAs.Value(i));
2388     if (aDT.IsNull())
2389       continue;
2390     Handle(XCAFDimTolObjects_DatumObject) aDatTargetObj = new XCAFDimTolObjects_DatumObject();
2391     XCAFDimTolObjects_DatumTargetType aType;
2392     if (!STEPCAFControl_GDTProperty::GetDatumTargetType(aDT->Description(), aType))
2393       continue;
2394     aDatTargetObj->SetDatumTargetType(aType);
2395     Standard_Boolean isValidDT = Standard_False;
2396
2397     // Feature for datum target
2398     TDF_LabelSequence aDTShapeLabels;
2399     Interface_EntityIterator aDTIter = aGraph.Sharings(aDT);
2400     Handle(StepRepr_FeatureForDatumTargetRelationship) aRelationship;
2401     for (; aDTIter.More() && aRelationship.IsNull(); aDTIter.Next()) {
2402       aRelationship = Handle(StepRepr_FeatureForDatumTargetRelationship)::DownCast(aDTIter.Value());
2403     }
2404     if (!aRelationship.IsNull()) {
2405       Handle(StepRepr_ShapeAspect) aSA = aRelationship->RelatingShapeAspect();
2406       Interface_EntityIterator aSAIter = aGraph.Sharings(aSA);
2407       for (; aSAIter.More(); aSAIter.Next()) {
2408         Handle(StepAP242_GeometricItemSpecificUsage) aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(aSAIter.Value());
2409         if (aGISU.IsNull())
2410           continue;
2411         for (Standard_Integer j = 1; j <= aGISU->NbIdentifiedItem(); j++) {
2412           TDF_Label aShapeL = getShapeLabel(aGISU->IdentifiedItemValue(j), theWS, aSTool);
2413           if (!aShapeL.IsNull()) {
2414             aDTShapeLabels.Append(aShapeL);
2415             isValidDT = Standard_True;
2416           }
2417         }
2418       }
2419     }
2420
2421     if (aType != XCAFDimTolObjects_DatumTargetType_Area && !isValidDT) {
2422       // Try another way of feature connection
2423       for (aDTIter.Start(); aDTIter.More(); aDTIter.Next()) {
2424         Handle(StepAP242_GeometricItemSpecificUsage) aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(aDTIter.Value());
2425         if (aGISU.IsNull())
2426           continue;
2427         for (Standard_Integer j = 1; j <= aGISU->NbIdentifiedItem(); j++) {
2428           TDF_Label aShapeL = getShapeLabel(aGISU->IdentifiedItemValue(j), theWS, aSTool);
2429           if (!aShapeL.IsNull()) {
2430             aDTShapeLabels.Append(aShapeL);
2431             isValidDT = Standard_True;
2432           }
2433         }
2434       }
2435     }
2436
2437     if (aType == XCAFDimTolObjects_DatumTargetType_Area) {
2438       // Area datum target
2439       Interface_EntityIterator anIterDTF = aGraph.Shareds(aDT);
2440       Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2441       for (; anIterDTF.More() && aGISU.IsNull(); anIterDTF.Next()) {
2442         aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDTF.Value());
2443       }
2444       Handle(StepRepr_RepresentationItem) anItem;
2445       if (aGISU->NbIdentifiedItem() > 0)
2446         anItem = aGISU->IdentifiedItemValue(1);
2447       if (anItem.IsNull())
2448         continue;
2449       Standard_Integer anItemIndex = FindShapeIndexForDGT(anItem, theWS);
2450       if (anItemIndex > 0) {
2451         Handle(Transfer_Binder) aBinder = aTP->MapItem(anItemIndex);
2452         TopoDS_Shape anItemShape = TransferBRep::ShapeResult(aBinder);
2453         aDatTargetObj->SetDatumTarget(anItemShape);
2454         isValidDT = Standard_True;
2455       }
2456     }
2457     else {
2458       // Point/line/rectangle/circle datum targets 
2459       Interface_EntityIterator anIter = aGraph.Sharings(aDT);
2460       Handle(StepRepr_PropertyDefinition) aPD;
2461       for (; anIter.More() && aPD.IsNull(); anIter.Next()) {
2462         aPD = Handle(StepRepr_PropertyDefinition)::DownCast(anIter.Value());
2463       }
2464       if (!aPD.IsNull()) {
2465         anIter = aGraph.Sharings(aPD);
2466         Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
2467         for (; anIter.More() && aSDR.IsNull(); anIter.Next()) {
2468           aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(anIter.Value());
2469         }
2470         if (!aSDR.IsNull()) {
2471           Handle(StepShape_ShapeRepresentationWithParameters) aSRWP
2472             = Handle(StepShape_ShapeRepresentationWithParameters)::DownCast(aSDR->UsedRepresentation());
2473           if (!aSRWP.IsNull()) {
2474             isValidDT = Standard_True;
2475             // Collect parameters of datum target
2476             for (Standard_Integer j = aSRWP->Items()->Lower(); j <= aSRWP->Items()->Upper(); j++)
2477             {
2478               if (aSRWP->ItemsValue(j).IsNull())
2479                 continue;
2480               if (aSRWP->ItemsValue(j)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2481               {
2482                 Handle(StepGeom_Axis2Placement3d) anAx
2483                   = Handle(StepGeom_Axis2Placement3d)::DownCast(aSRWP->ItemsValue(j));
2484                 XSAlgo::AlgoContainer()->PrepareForTransfer();
2485                 STEPControl_ActorRead anActor;
2486                 anActor.PrepareUnits(aSRWP, aTP);
2487                 Handle(Geom_Axis2Placement) anAxis = StepToGeom::MakeAxis2Placement(anAx);
2488                 aDatTargetObj->SetDatumTargetAxis(anAxis->Ax2());
2489               }
2490               else if (aSRWP->ItemsValue(j)->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit)))
2491               {
2492                 Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aM =
2493                   Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aSRWP->ItemsValue(j));
2494                 Standard_Real aVal = aM->GetMeasureWithUnit()->ValueComponent();
2495                 StepBasic_Unit anUnit = aM->GetMeasureWithUnit()->UnitComponent();
2496                 if (anUnit.IsNull())
2497                   continue;
2498                 Handle(StepBasic_NamedUnit) aNU = anUnit.NamedUnit();
2499                 if (aNU.IsNull())
2500                   continue;
2501                 STEPConstruct_UnitContext anUnitCtx;
2502                 anUnitCtx.ComputeFactors(aNU);
2503                 aVal = aVal * anUnitCtx.LengthFactor();
2504                 if (aM->Name()->String().IsEqual("target length") ||
2505                   aM->Name()->String().IsEqual("target diameter"))
2506                   aDatTargetObj->SetDatumTargetLength(aVal);
2507                 else
2508                   aDatTargetObj->SetDatumTargetWidth(aVal);
2509               }
2510             }
2511           }
2512         }
2513       }
2514     }
2515
2516     // Create datum target object
2517     if (isValidDT) {
2518       TDF_Label aDatL = aDGTTool->AddDatum();
2519       myGDTMap.Bind(aDT, aDatL);
2520       aDGTTool->Lock(aDatL);
2521       aDat = XCAFDoc_Datum::Set(aDatL);
2522       aDGTTool->SetDatum(aDTShapeLabels, aDatL);
2523       aDatTargetObj->SetName(theDat->Identification());
2524       aDatTargetObj->SetPosition(thePositionCounter);
2525       if (!theXCAFModifiers.IsEmpty())
2526         aDatTargetObj->SetModifiers(theXCAFModifiers);
2527       if (theXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None)
2528         aDatTargetObj->SetModifierWithValue(theXCAFModifWithVal, theModifValue);
2529       aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2530       aDatTargetObj->IsDatumTarget(Standard_True);
2531       aDatTargetObj->SetDatumTargetNumber(aDT->TargetId()->IntegerValue());
2532       readAnnotation(aTR, aDT, aDatTargetObj);
2533       aDat->SetObject(aDatTargetObj);
2534       isExistDatumTarget = Standard_True;
2535     }
2536   }
2537
2538   if (aShapeLabels.Length() > 0 || !isExistDatumTarget) {
2539     // Create object for datum
2540     TDF_Label aDatL = aDGTTool->AddDatum();
2541     myGDTMap.Bind(theDat, aDatL);
2542     // bind datum label with all reference datum_feature entities
2543     for (Standard_Integer i = 1; i <= aSAs.Length(); i++) {
2544       Handle(StepRepr_ShapeAspect) aSA = aSAs.Value(i);
2545       if (aSA.IsNull() || aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)))
2546         continue;
2547       myGDTMap.Bind(aSA, aDatL);
2548     }
2549     aDGTTool->Lock(aDatL);
2550     aDat = XCAFDoc_Datum::Set(aDatL);
2551     aDGTTool->SetDatum(aShapeLabels, aDatL);
2552     aDatObj->SetName(theDat->Identification());
2553     aDatObj->SetPosition(thePositionCounter);
2554     if (!theXCAFModifiers.IsEmpty())
2555       aDatObj->SetModifiers(theXCAFModifiers);
2556     if (theXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None)
2557       aDatObj->SetModifierWithValue(theXCAFModifWithVal, theModifValue);
2558     aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2559     if (aDatObj->GetPresentation().IsNull()) {
2560       // Try find annotation connected to datum entity (not right case, according recommended practices)
2561       readAnnotation(aTR, theDat, aDatObj);
2562     }
2563     aDat->SetObject(aDatObj);
2564   }
2565
2566   return Standard_True;
2567 }
2568
2569
2570 //=======================================================================
2571 //function : ReadDatums
2572 //purpose  : auxilary
2573 //=======================================================================
2574 Standard_Boolean STEPCAFControl_Reader::readDatumsAP242(const Handle(Standard_Transient)& theEnt,
2575   const TDF_Label theGDTL,
2576   const Handle(TDocStd_Document)& theDoc,
2577   const Handle(XSControl_WorkSession)& theWS)
2578 {
2579   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2580   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2581   const Interface_Graph& aGraph = aTP->Graph();
2582
2583   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2584   for (anIter.Start(); anIter.More(); anIter.Next()) {
2585     Handle(Standard_Transient) anAtr = anIter.Value();
2586     if (anAtr->IsKind(STANDARD_TYPE(StepDimTol_DatumSystem)))
2587     {
2588       Standard_Integer aPositionCounter = 0;//position on frame 
2589       Handle(StepDimTol_DatumSystem) aDS = Handle(StepDimTol_DatumSystem)::DownCast(anAtr);
2590       Interface_EntityIterator anIterDS = aGraph.Sharings(aDS);
2591       for (anIterDS.Start(); anIterDS.More(); anIterDS.Next()) {
2592         Handle(Standard_Transient) anAtrDS = anIterDS.Value();
2593         if (anAtrDS->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2594         {
2595           //get axis
2596           Handle(StepAP242_GeometricItemSpecificUsage)aAxGISUI
2597             = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anAtrDS);
2598           if (aAxGISUI->IdentifiedItemValue(1)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2599           {
2600             Handle(StepGeom_Axis2Placement3d) anAx
2601               = Handle(StepGeom_Axis2Placement3d)::DownCast(aAxGISUI->IdentifiedItemValue(1));
2602             Handle(XCAFDoc_GeomTolerance) aTol;
2603             if (theGDTL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aTol))
2604             {
2605               Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aTol->GetObject();
2606               Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2607               Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2608               Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2609               gp_Dir aDir;
2610               gp_Dir aDirR;
2611               gp_Pnt aPnt;
2612               if (!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2613                 !aDirRArr.IsNull() && aDirRArr->Length() > 2 &&
2614                 !aLocArr.IsNull() && aLocArr->Length() > 2)
2615               {
2616                 aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower() + 1, aDirArr->Lower() + 2);
2617                 aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower() + 1, aDirRArr->Lower() + 2);
2618                 aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower() + 1, aLocArr->Lower() + 2);
2619                 gp_Ax2 anA(aPnt, aDir, aDirR);
2620                 anObj->SetAxis(anA);
2621                 aTol->SetObject(anObj);
2622               }
2623             }
2624           }
2625         }
2626       }
2627       if (aDS->NbConstituents() > 0)
2628       {
2629         //get datum feature and datum target from datum system
2630         Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aDRCA = aDS->Constituents();
2631         if (!aDRCA.IsNull())
2632         {
2633           for (Standard_Integer i = aDRCA->Lower(); i <= aDRCA->Upper(); i++)
2634           {
2635             Handle(StepDimTol_DatumReferenceCompartment) aDRC = aDRCA->Value(i);
2636             //gete modifiers
2637             Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModif = aDRC->Modifiers();
2638             XCAFDimTolObjects_DatumModifiersSequence aXCAFModifiers;
2639             XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal = XCAFDimTolObjects_DatumModifWithValue_None;
2640             Standard_Real aModifValue = 0;
2641             if (!aModif.IsNull())
2642             {
2643               for (Standard_Integer m = aModif->Lower(); m <= aModif->Upper(); m++)
2644               {
2645                 if (aModif->Value(m).CaseNumber() == 2)
2646                   aXCAFModifiers.Append(
2647                   (XCAFDimTolObjects_DatumSingleModif)aModif->Value(m).
2648                     SimpleDatumReferenceModifierMember()->Value());
2649                 else if (aModif->Value(m).CaseNumber() == 1)
2650                 {
2651                   aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModif->Value(m).DatumReferenceModifierWithValue()->ModifierType() + 1);
2652                   Standard_Real aVal = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2653                   StepBasic_Unit anUnit = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2654                   if (anUnit.IsNull()) continue;
2655                   if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2656                   Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2657                   STEPConstruct_UnitContext anUnitCtx;
2658                   anUnitCtx.ComputeFactors(NU);
2659                   aModifValue = aVal * anUnitCtx.LengthFactor();
2660                 }
2661               }
2662             }
2663             aPositionCounter++;
2664             Interface_EntityIterator anIterDRC = aGraph.Shareds(aDRC);
2665             for (anIterDRC.Start(); anIterDRC.More(); anIterDRC.Next()) {
2666
2667               if (anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2668               {
2669                 Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRC.Value());
2670                 setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue, theDoc, theWS);
2671               }
2672               else if (anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_DatumReferenceElement)))
2673               {
2674                 Handle(StepDimTol_DatumReferenceElement) aDRE
2675                   = Handle(StepDimTol_DatumReferenceElement)::DownCast(anIterDRC.Value());
2676                 //get modifiers from group of datums
2677                 Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifE = aDRE->Modifiers();
2678                 if (!aModifE.IsNull())
2679                 {
2680                   for (Standard_Integer k = aModifE->Lower(); k <= aModifE->Upper(); k++)
2681                   {
2682                     if (aModifE->Value(k).CaseNumber() == 2)
2683                       aXCAFModifiers.Append(
2684                       (XCAFDimTolObjects_DatumSingleModif)aModifE->Value(k).
2685                         SimpleDatumReferenceModifierMember()->Value());
2686                     else if (aModifE->Value(k).CaseNumber() == 1)
2687                     {
2688                       aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierType() + 1);
2689                       Standard_Real aVal = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2690                       StepBasic_Unit anUnit = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2691                       if (anUnit.IsNull()) continue;
2692                       if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2693                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2694                       STEPConstruct_UnitContext anUnitCtx;
2695                       anUnitCtx.ComputeFactors(NU);
2696                       aModifValue = aVal * anUnitCtx.LengthFactor();
2697                     }
2698                   }
2699                 }
2700                 Interface_EntityIterator anIterDRE = aGraph.Shareds(aDRE);
2701                 for (anIterDRE.Start(); anIterDRE.More(); anIterDRE.Next()) {
2702                   if (anIterDRE.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2703                   {
2704                     Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRE.Value());
2705                     setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue, theDoc, theWS);
2706                   }
2707                 }
2708               }
2709             }
2710           }
2711         }
2712       }
2713     }
2714   }
2715   return Standard_True;
2716 }
2717
2718 //=======================================================================
2719 //function : createGeomTolObjectInXCAF
2720 //purpose  : 
2721 //=======================================================================
2722 TDF_Label STEPCAFControl_Reader::createGDTObjectInXCAF(const Handle(Standard_Transient)& theEnt,
2723   const Handle(TDocStd_Document)& theDoc,
2724   const Handle(XSControl_WorkSession)& theWS)
2725 {
2726   TDF_Label aGDTL;
2727   if (!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2728     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) &&
2729     !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2730   {
2731     return aGDTL;
2732   }
2733
2734   Handle(TCollection_HAsciiString) aSemanticName;
2735
2736   // protection against invalid input
2737   if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2738     Handle(StepDimTol_GeometricTolerance) aGeomTol = Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2739     if (aGeomTol->TolerancedShapeAspect().IsNull())
2740       return aGDTL;
2741     aSemanticName = aGeomTol->Name();
2742   }
2743   if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2744     Handle(StepShape_DimensionalSize) aDim = Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2745     if (aDim->AppliesTo().IsNull())
2746       return aGDTL;
2747     aSemanticName = aDim->Name();
2748   }
2749   if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2750     Handle(StepShape_DimensionalLocation) aDim = Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
2751     if (aDim->RelatedShapeAspect().IsNull() || aDim->RelatingShapeAspect().IsNull())
2752       return aGDTL;
2753     aSemanticName = aDim->Name();
2754   }
2755
2756   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
2757   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
2758   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2759   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2760   const Interface_Graph& aGraph = aTP->Graph();
2761   Standard_Boolean isAllAround = Standard_False;
2762   Standard_Boolean isAllOver = Standard_False;
2763
2764   // find RepresentationItem for current Ent
2765   NCollection_Sequence<Handle(Standard_Transient)> aSeqRI1, aSeqRI2;
2766
2767   // Collect all Shape_Aspect entities
2768   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2769   for (anIter.Start(); anIter.More(); anIter.Next()) {
2770     Handle(Standard_Transient) anAtr = anIter.Value();
2771     NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2772     if (anAtr->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)))
2773     {
2774       //if associating tolerances with part (All-Over)
2775       Interface_EntityIterator anIterSDR = aGraph.Sharings(anAtr);
2776       for (anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next())
2777       {
2778         Handle(Standard_Transient) anAtrSDR = anIterSDR.Value();
2779         if (anAtrSDR->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2780         {
2781           isAllOver = Standard_True;
2782           Interface_EntityIterator anIterABSR = aGraph.Shareds(anAtrSDR);
2783           for (anIterABSR.Start(); anIterABSR.More(); anIterABSR.Next())
2784           {
2785             Handle(Standard_Transient) anAtrABSR = anIterABSR.Value();
2786             if (anAtrABSR->IsKind(STANDARD_TYPE(StepShape_AdvancedBrepShapeRepresentation)))
2787             {
2788               aSeqRI1.Append(anAtrABSR);
2789             }
2790           }
2791         }
2792       }
2793     }
2794     else if (anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
2795       anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2796     {
2797       //if tolerance attached to dimension
2798       Interface_EntityIterator anIterDim = aGraph.Shareds(anAtr);
2799       for (anIterDim.Start(); anIterDim.More(); anIterDim.Next())
2800       {
2801         Handle(StepRepr_ShapeAspect) aSA = Handle(StepRepr_ShapeAspect)::DownCast(anIterDim.Value());
2802         if (!aSA.IsNull()) {
2803           collectShapeAspect(aSA, theWS, aSAs);
2804         }
2805       }
2806     }
2807     else if (anAtr->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2808     {
2809       if (anAtr->IsKind(STANDARD_TYPE(StepRepr_AllAroundShapeAspect)))
2810       {
2811         // if applyed AllAround Modifier
2812         isAllAround = Standard_True;
2813       }
2814       // dimensions and default tolerances
2815       Handle(StepRepr_ShapeAspect) aSA = Handle(StepRepr_ShapeAspect)::DownCast(anAtr);
2816       if (!aSA.IsNull()) {
2817         collectShapeAspect(aSA, theWS, aSAs);
2818       }
2819     }
2820
2821     // Collect all representation items
2822     if (!aSAs.IsEmpty())
2823     {
2824       //get representation items
2825       NCollection_Sequence<Handle(Standard_Transient)> aSeqRI;
2826       for (Standard_Integer i = aSAs.Lower(); i <= aSAs.Upper(); i++)
2827       {
2828         Interface_EntityIterator anIterSA = aGraph.Sharings(aSAs.Value(i));
2829         Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2830         Handle(StepRepr_PropertyDefinition) PropD;
2831         for (anIterSA.Start(); anIterSA.More() && aGISU.IsNull() && PropD.IsNull(); anIterSA.Next()) {
2832           aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2833           PropD = Handle(StepRepr_PropertyDefinition)::DownCast(anIterSA.Value());
2834         }
2835         if (!PropD.IsNull())//for old version
2836         {
2837           Handle(StepRepr_RepresentationItem) RI;
2838           Interface_EntityIterator subs4 = aGraph.Sharings(PropD);
2839           for (subs4.Start(); subs4.More(); subs4.Next()) {
2840             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
2841               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
2842             if (!SDR.IsNull()) {
2843               Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2844               if (!Repr.IsNull() && Repr->NbItems() > 0) {
2845                 RI = Repr->ItemsValue(1);
2846               }
2847             }
2848           }
2849           if (RI.IsNull()) continue;
2850
2851           if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2852             // read dimensions
2853             Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
2854             if (EC.IsNull()) continue;
2855             Handle(TCollection_HAsciiString) aName;
2856             Handle(StepShape_DimensionalSize) DimSize =
2857               Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2858             Standard_Real dim1 = -1., dim2 = -1.;
2859             subs4 = aGraph.Sharings(DimSize);
2860             for (subs4.Start(); subs4.More(); subs4.Next()) {
2861               Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR =
2862                 Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
2863               if (!DimCharR.IsNull()) {
2864                 Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
2865                 if (!SDimR.IsNull() && SDimR->NbItems() > 0) {
2866                   Handle(StepRepr_RepresentationItem) anItem = SDimR->ItemsValue(1);
2867                   Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(anItem);
2868                   if (!VR.IsNull()) {
2869                     aName = VR->Name();
2870                     //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
2871                     //if(CID.IsNull()) continue;
2872                     //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
2873                     //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
2874                     //if(CIDM.IsNull()) continue;
2875                     //if(CIDM->ArrTransient().IsNull()) continue;
2876                     //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
2877                     //if(CID.CaseMem(CIDM)==1)
2878                     //  HARI = CID.ListRepresentationItem();
2879                     //if(CID.CaseMem(CIDM)==2)
2880                     //  HARI = CID.SetRepresentationItem();
2881                     Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
2882                     if (HARI.IsNull()) continue;
2883                     if (HARI->Length() > 0) {
2884                       Handle(StepRepr_RepresentationItem) RI1 = HARI->Value(1);
2885                       if (RI1.IsNull()) continue;
2886                       if (RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2887                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2888                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
2889                         dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2890                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2891                         if (anUnit.IsNull()) continue;
2892                         if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2893                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2894                         STEPConstruct_UnitContext anUnitCtx;
2895                         anUnitCtx.ComputeFactors(NU);
2896                         dim1 = dim1 * anUnitCtx.LengthFactor();
2897                       }
2898                     }
2899                     if (HARI->Length() > 1) {
2900                       Handle(StepRepr_RepresentationItem) RI2 = HARI->Value(2);
2901                       if (RI2.IsNull()) continue;
2902                       if (RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2903                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2904                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
2905                         dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2906                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2907                         if (anUnit.IsNull()) continue;
2908                         if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2909                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2910                         STEPConstruct_UnitContext anUnitCtx;
2911                         anUnitCtx.ComputeFactors(NU);
2912                         dim2 = dim2 * anUnitCtx.LengthFactor();
2913                       }
2914                     }
2915                   }
2916                 }
2917               }
2918             }
2919             if (dim1 < 0) continue;
2920             if (dim2 < 0) dim2 = dim1;
2921             //std::cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<std::endl;
2922             // now we know edge_curve and value range therefore
2923             // we can create corresponding D&GT labels
2924             Standard_Integer index = aTP->MapIndex(EC);
2925             TopoDS_Shape aSh;
2926             if (index > 0) {
2927               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2928               aSh = TransferBRep::ShapeResult(binder);
2929             }
2930             if (aSh.IsNull()) continue;
2931             TDF_Label shL;
2932             if (!aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True)) continue;
2933             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1, 2);
2934             arr->SetValue(1, dim1);
2935             arr->SetValue(2, dim2);
2936             aDGTTool->SetDimTol(shL, 1, arr, aName, DimSize->Name());
2937           }
2938           // read tolerances and datums
2939           else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2940             Handle(StepDimTol_GeometricTolerance) GT =
2941               Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2942             // read common data for tolerance
2943             //Standard_Real dim = GT->Magnitude()->ValueComponent();
2944             Handle(StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
2945             if (dim3.IsNull()) continue;
2946             Standard_Real dim = dim3->ValueComponent();
2947             StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
2948             if (anUnit.IsNull()) continue;
2949             if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2950             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2951             STEPConstruct_UnitContext anUnitCtx;
2952             anUnitCtx.ComputeFactors(NU);
2953             dim = dim * anUnitCtx.LengthFactor();
2954             //std::cout<<"GeometricTolerance: Magnitude = "<<dim<<std::endl;
2955             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1, 1);
2956             arr->SetValue(1, dim);
2957             Handle(TCollection_HAsciiString) aName = GT->Name();
2958             Handle(TCollection_HAsciiString) aDescription = GT->Description();
2959             Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2960             if (AF.IsNull()) continue;
2961             Standard_Integer index = aTP->MapIndex(AF);
2962             TopoDS_Shape aSh;
2963             if (index > 0) {
2964               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2965               aSh = TransferBRep::ShapeResult(binder);
2966             }
2967             if (aSh.IsNull()) continue;
2968             TDF_Label shL;
2969             if (!aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True)) continue;
2970             // read specific data for tolerance
2971             if (GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
2972               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2973                 Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(theEnt);
2974               Standard_Integer kind = 20;
2975               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2976                 GTComplex->GetModifiedGeometricTolerance();
2977               if (!MGT.IsNull()) {
2978                 kind = kind + MGT->Modifier() + 1;
2979               }
2980               TDF_Label TolerL = aDGTTool->SetDimTol(shL, kind, arr, aName, aDescription);
2981               // translate datums connected with this tolerance
2982               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2983                 GTComplex->GetGeometricToleranceWithDatumReference();
2984               if (!GTWDR.IsNull()) {
2985                 ReadDatums(aSTool, aDGTTool, aGraph, aTP, TolerL, GTWDR);
2986               }
2987             }
2988             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
2989               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2990                 Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(theEnt);
2991               if (GTWDR.IsNull()) continue;
2992               Standard_Integer kind = 0;
2993               if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
2994               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
2995               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
2996               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
2997               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
2998               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
2999               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
3000               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
3001               //std::cout<<"GTWDR: kind="<<kind<<std::endl;
3002               TDF_Label TolerL = aDGTTool->SetDimTol(shL, kind, arr, aName, aDescription);
3003               ReadDatums(aSTool, aDGTTool, aGraph, aTP, TolerL, GTWDR);
3004             }
3005             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
3006               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
3007                 Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(theEnt);
3008               Standard_Integer kind = 35 + MGT->Modifier();
3009               aDGTTool->SetDimTol(shL, kind, arr, aName, aDescription);
3010             }
3011             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
3012               aDGTTool->SetDimTol(shL, 38, arr, aName, aDescription);
3013             }
3014             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
3015               aDGTTool->SetDimTol(shL, 39, arr, aName, aDescription);
3016             }
3017             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
3018               aDGTTool->SetDimTol(shL, 40, arr, aName, aDescription);
3019             }
3020             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
3021               aDGTTool->SetDimTol(shL, 41, arr, aName, aDescription);
3022             }
3023             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
3024               aDGTTool->SetDimTol(shL, 42, arr, aName, aDescription);
3025             }
3026             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
3027               aDGTTool->SetDimTol(shL, 43, arr, aName, aDescription);
3028             }
3029             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
3030               aDGTTool->SetDimTol(shL, 44, arr, aName, aDescription);
3031             }
3032           }
3033         }
3034         else
3035         {
3036           if (aGISU.IsNull()) continue;
3037           Standard_Integer j = 1;
3038           for (; j <= aGISU->NbIdentifiedItem(); j++) {
3039             aSeqRI.Append(aGISU->IdentifiedItemValue(j));
3040           }
3041         }
3042       }
3043       if (!aSeqRI.IsEmpty())
3044       {
3045         if (aSeqRI1.IsEmpty())
3046           aSeqRI1 = aSeqRI;
3047         else
3048           aSeqRI2 = aSeqRI;
3049       }
3050     }
3051   }
3052   if (aSeqRI1.IsEmpty())
3053     return aGDTL;
3054
3055   TDF_LabelSequence aShLS1, aShLS2;
3056
3057   // Collect shapes
3058   for (Standard_Integer i = aSeqRI1.Lower(); i <= aSeqRI1.Upper();i++)
3059   {
3060     Standard_Integer anIndex = FindShapeIndexForDGT(aSeqRI1.Value(i), theWS);
3061     TopoDS_Shape aSh;
3062     if (anIndex > 0) {
3063       Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
3064       aSh = TransferBRep::ShapeResult(aBinder);
3065     }
3066     if (!aSh.IsNull())
3067     {
3068       TDF_Label aShL;
3069       aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
3070       if (aShL.IsNull() && aSh.ShapeType() == TopAbs_WIRE)
3071       {
3072         TopExp_Explorer ex(aSh, TopAbs_EDGE, TopAbs_SHAPE);
3073         while (ex.More())
3074         {
3075           TDF_Label edgeL;
3076           aSTool->Search(ex.Current(), edgeL, Standard_True, Standard_True, Standard_True);
3077           if (!edgeL.IsNull())
3078             aShLS1.Append(edgeL);
3079           ex.Next();
3080         }
3081       }
3082       if (!aShL.IsNull())
3083         aShLS1.Append(aShL);
3084     }
3085   }
3086   if (!aSeqRI2.IsEmpty())
3087   {
3088     //for dimensional location
3089     for (Standard_Integer i = aSeqRI2.Lower(); i <= aSeqRI2.Upper();i++)
3090     {
3091       Standard_Integer anIndex = FindShapeIndexForDGT(aSeqRI2.Value(i), theWS);
3092       TopoDS_Shape aSh;
3093       if (anIndex > 0) {
3094         Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
3095         aSh = TransferBRep::ShapeResult(aBinder);
3096       }
3097       if (!aSh.IsNull())
3098       {
3099         TDF_Label aShL;
3100         aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
3101         if (aShL.IsNull() && aSh.ShapeType() == TopAbs_WIRE)
3102         {
3103           TopExp_Explorer ex(aSh, TopAbs_EDGE, TopAbs_SHAPE);
3104           while (ex.More())
3105           {
3106             TDF_Label edgeL;
3107             aSTool->Search(ex.Current(), edgeL, Standard_True, Standard_True, Standard_True);
3108             if (!edgeL.IsNull())
3109               aShLS2.Append(edgeL);
3110             ex.Next();
3111           }
3112         }
3113         if (!aShL.IsNull())
3114           aShLS2.Append(aShL);
3115       }
3116     }
3117   }
3118
3119   if (!aShLS1.IsEmpty())
3120   {
3121     // add to XCAF
3122     if (!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
3123     {
3124       aGDTL = aDGTTool->AddDimension();
3125       myGDTMap.Bind(theEnt, aGDTL);
3126       aDGTTool->Lock(aGDTL);
3127       Handle(XCAFDoc_Dimension) aDim = XCAFDoc_Dimension::Set(aGDTL);
3128       TCollection_AsciiString aStr("DGT:Dimensional_");
3129       if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
3130       {
3131         aStr.AssignCat("Size");
3132       }
3133       else if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
3134       {
3135         aStr.AssignCat("Location");
3136       }
3137       TDataStd_Name::Set(aGDTL, aStr);
3138
3139       if (!aShLS2.IsEmpty())
3140       {
3141         aDGTTool->SetDimension(aShLS1, aShLS2, aGDTL);
3142       }
3143       else
3144       {
3145         TDF_LabelSequence aEmptySeq;
3146         aDGTTool->SetDimension(aShLS1, aEmptySeq, aGDTL);
3147       }
3148     }
3149     else
3150     {
3151       aGDTL = aDGTTool->AddGeomTolerance();
3152       myGDTMap.Bind(theEnt, aGDTL);
3153       aDGTTool->Lock(aGDTL);
3154       Handle(XCAFDoc_GeomTolerance) aGTol = XCAFDoc_GeomTolerance::Set(aGDTL);
3155       TCollection_AsciiString aStr("DGT:GeomTolerance");
3156       TDataStd_Name::Set(aGDTL, aStr);
3157       aDGTTool->SetGeomTolerance(aShLS1, aGDTL);
3158       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aGTol->GetObject();
3159       if (isAllAround)
3160         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Around);
3161       else if (isAllOver)
3162         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Over);
3163       aGTol->SetObject(anObj);
3164     }
3165
3166     if (aSemanticName)
3167     {
3168       TCollection_ExtendedString str(aSemanticName->String());
3169       TDataStd_Name::Set(aGDTL, str);
3170     }
3171
3172     readDatumsAP242(theEnt, aGDTL, theDoc, theWS);
3173   }
3174   return aGDTL;
3175 }
3176
3177 //=======================================================================
3178 //function : convertAngleValue
3179 //purpose  : auxilary
3180 //=======================================================================
3181 void convertAngleValue(
3182   const STEPConstruct_UnitContext& anUnitCtx,
3183   Standard_Real& aVal)
3184 {
3185   // convert radian to deg
3186   Standard_Real aFact = anUnitCtx.PlaneAngleFactor() * 180 / M_PI;
3187   // in order to avoid inaccuracy of calculation perform conversion
3188   // only if aFact not eqaul 1 with some precision
3189   if (fabs(1. - aFact) > Precision::Confusion())
3190   {
3191     aVal = aVal * aFact;
3192   }
3193 }
3194
3195
3196 //=======================================================================
3197 //function : setDimObjectToXCAF
3198 //purpose  : 
3199 //=======================================================================
3200 static void setDimObjectToXCAF(const Handle(Standard_Transient)& theEnt,
3201   const TDF_Label& aDimL,
3202   const Handle(TDocStd_Document)& theDoc,
3203   const Handle(XSControl_WorkSession)& theWS)
3204 {
3205   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
3206   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
3207   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
3208   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
3209   const Interface_Graph& aGraph = aTP->Graph();
3210   Handle(XCAFDimTolObjects_DimensionObject) aDimObj;
3211   if (!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
3212     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
3213     return;
3214
3215   Handle(StepShape_DimensionalSize) aDimSize =
3216     Handle(StepShape_DimensionalSize)::DownCast(theEnt);
3217   Handle(StepShape_DimensionalLocation) aDimLocation =
3218     Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
3219
3220   aDimObj = new XCAFDimTolObjects_DimensionObject();
3221   Standard_Real aDim1 = -1., aDim2 = -1., aDim3 = -1.;
3222   Standard_Boolean isPlusMinusTolerance = Standard_False;
3223   Handle(StepShape_TypeQualifier) aTQ;
3224   Handle(StepShape_ValueFormatTypeQualifier) aVFTQ;
3225   Handle(StepShape_ToleranceValue) aTV;
3226   Handle(StepShape_LimitsAndFits) aLAF;
3227   Handle(StepRepr_CompoundRepresentationItem) aCRI;
3228   Handle(StepGeom_Axis2Placement3d) anAP;
3229
3230   Interface_EntityIterator anIterDim;
3231   if (!aDimSize.IsNull())
3232   {
3233     anIterDim = aGraph.Sharings(aDimSize);
3234   }
3235   else
3236   {
3237     anIterDim = aGraph.Sharings(aDimLocation);
3238   }
3239   for (anIterDim.Start(); anIterDim.More(); anIterDim.Next()) {
3240     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR =
3241       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anIterDim.Value());
3242     Handle(StepShape_PlusMinusTolerance) aPMT =
3243       Handle(StepShape_PlusMinusTolerance)::DownCast(anIterDim.Value());
3244     if (!aDCR.IsNull()) {
3245       Handle(StepShape_ShapeDimensionRepresentation) aSDR = aDCR->Representation();
3246       if (!aSDR.IsNull()) {
3247         Handle(StepRepr_HArray1OfRepresentationItem) aHARI = aSDR->Items();
3248
3249         if (!aHARI.IsNull())
3250         {
3251           for (Standard_Integer nr = aHARI->Lower(); nr <= aHARI->Upper(); nr++)
3252           {
3253             Handle(StepRepr_RepresentationItem) aDRI = aHARI->Value(nr);
3254             if (aDRI.IsNull()) continue;
3255
3256             if (aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnit))) {
3257               // simple value / range
3258               Handle(StepRepr_ReprItemAndMeasureWithUnit) aMWU =
3259                 Handle(StepRepr_ReprItemAndMeasureWithUnit)::DownCast(aDRI);
3260               Standard_Real aVal = aMWU->GetMeasureWithUnit()->ValueComponent();
3261               StepBasic_Unit anUnit = aMWU->GetMeasureWithUnit()->UnitComponent();
3262               if (anUnit.IsNull())
3263                 continue;
3264               if (!(anUnit.CaseNum(anUnit.Value()) == 1))
3265                 continue;
3266               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3267               STEPConstruct_UnitContext anUnitCtx;
3268               anUnitCtx.ComputeFactors(NU);
3269               if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
3270                 aVal = aVal * anUnitCtx.LengthFactor();
3271
3272               }
3273               else
3274                 if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit))) {
3275                   convertAngleValue(anUnitCtx, aVal);
3276                 }
3277               Handle(TCollection_HAsciiString) aName = aMWU->Name();
3278               if (aName->Search("upper") > 0) // upper limit
3279                 aDim2 = aVal;
3280               else // lower limit or simple nominal value
3281                 aDim1 = aVal;
3282             }
3283             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnitAndQRI))) {
3284               // value with qualifier (minimum/maximum/average)
3285               Handle(StepRepr_ReprItemAndMeasureWithUnitAndQRI) aMWU =
3286                 Handle(StepRepr_ReprItemAndMeasureWithUnitAndQRI)::DownCast(aDRI);
3287               Standard_Real aVal = aMWU->GetMeasureWithUnit()->ValueComponent();
3288               StepBasic_Unit anUnit = aMWU->GetMeasureWithUnit()->UnitComponent();
3289               if (anUnit.IsNull())
3290                 continue;
3291               if (!(anUnit.CaseNum(anUnit.Value()) == 1))
3292                 continue;
3293               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3294               STEPConstruct_UnitContext anUnitCtx;
3295               anUnitCtx.ComputeFactors(NU);
3296               if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI))) {
3297                 aVal = aVal * anUnitCtx.LengthFactor();
3298               }
3299               else
3300                 if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI))) {
3301                   convertAngleValue(anUnitCtx, aVal);
3302                 }
3303               Handle(StepShape_QualifiedRepresentationItem) aQRI = aMWU->GetQualifiedRepresentationItem();
3304               if (aQRI->Qualifiers()->Length() == 0) {
3305                 aDim1 = aVal;
3306                 continue;
3307               }
3308               Handle(StepShape_TypeQualifier) aValueType = aQRI->Qualifiers()->Value(1).TypeQualifier();
3309               if (aValueType->Name()->String().IsEqual("minimum"))
3310                 aDim2 = aVal;
3311               else if (aValueType->Name()->String().IsEqual("maximum"))
3312                 aDim3 = aVal;
3313               else aDim1 = aVal;
3314             }
3315             else if (aDRI->IsKind(STANDARD_TYPE(StepShape_QualifiedRepresentationItem))) {
3316               //get qualifier
3317               Handle(StepShape_QualifiedRepresentationItem) aQRI =
3318                 Handle(StepShape_QualifiedRepresentationItem)::DownCast(aDRI);
3319               for (Standard_Integer l = 1; l <= aQRI->NbQualifiers(); l++)
3320               {
3321                 aTQ = aQRI->Qualifiers()->Value(l).TypeQualifier();
3322                 aVFTQ = aQRI->Qualifiers()->Value(l).ValueFormatTypeQualifier();
3323               }
3324             }
3325             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
3326               Handle(StepRepr_DescriptiveRepresentationItem) aDescription =
3327                 Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(aDRI);
3328               aDimObj->AddDescription(aDescription->Description(), aDescription->Name());
3329             }
3330             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_CompoundRepresentationItem))) {
3331               aCRI = Handle(StepRepr_CompoundRepresentationItem)::DownCast(aDRI);
3332             }
3333             else if (aDRI->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
3334             {
3335               anAP = Handle(StepGeom_Axis2Placement3d)::DownCast(aDRI);
3336             }
3337           }
3338         }
3339       }
3340     }
3341     else if (!aPMT.IsNull())
3342     {
3343       isPlusMinusTolerance = Standard_True;
3344       StepShape_ToleranceMethodDefinition aTMD = aPMT->Range();
3345       if (aPMT.IsNull()) continue;
3346       if (aTMD.CaseNumber() == 1)
3347         //! 1 -> ToleranceValue from StepShape
3348         //! 2 -> LimitsAndFits from StepShape
3349       {
3350         //plus minus tolerance 
3351         aTV = aTMD.ToleranceValue();
3352         if (aTV.IsNull()) continue;
3353
3354         Handle(Standard_Transient) aUpperBound = aTV->UpperBound();
3355         if(aUpperBound.IsNull())
3356           continue;
3357         Handle(StepBasic_MeasureWithUnit) aMWU;
3358         if(aUpperBound->IsKind(STANDARD_TYPE(StepBasic_MeasureWithUnit)) )
3359           aMWU = Handle(StepBasic_MeasureWithUnit)::DownCast(aUpperBound);
3360         else if(aUpperBound->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnit)) )
3361         {
3362           Handle(StepRepr_ReprItemAndMeasureWithUnit) aReprMeasureItem = 
3363             Handle(StepRepr_ReprItemAndMeasureWithUnit)::DownCast(aUpperBound);
3364           aMWU = aReprMeasureItem->GetMeasureWithUnit();
3365
3366         }
3367         if(aMWU.IsNull())
3368           continue;
3369         Standard_Real aVal = aMWU->ValueComponent();
3370         StepBasic_Unit anUnit = aMWU->UnitComponent();
3371         if (anUnit.IsNull()) continue;
3372         if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
3373         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3374         STEPConstruct_UnitContext anUnitCtx;
3375         anUnitCtx.ComputeFactors(NU);
3376         if (aMWU->IsKind(STANDARD_TYPE(StepBasic_LengthMeasureWithUnit)) ||
3377           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI)))
3378         {
3379           aVal = aVal * anUnitCtx.LengthFactor();
3380         }
3381         else if (aMWU->IsKind(STANDARD_TYPE(StepBasic_PlaneAngleMeasureWithUnit)) ||
3382           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI)))
3383         {
3384           convertAngleValue(anUnitCtx, aVal);
3385         }
3386         aDim3 = aVal;
3387
3388         
3389         Handle(Standard_Transient) aLowerBound = aTV->LowerBound();
3390         if(aLowerBound.IsNull())
3391           continue;
3392        
3393         if(aLowerBound->IsKind(STANDARD_TYPE(StepBasic_MeasureWithUnit)) )
3394           aMWU = Handle(StepBasic_MeasureWithUnit)::DownCast(aLowerBound);
3395         else if(aLowerBound->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnit)) )
3396         {
3397           Handle(StepRepr_ReprItemAndMeasureWithUnit) aReprMeasureItem = 
3398             Handle(StepRepr_ReprItemAndMeasureWithUnit)::DownCast(aLowerBound);
3399           aMWU = aReprMeasureItem->GetMeasureWithUnit();
3400
3401         }
3402         if(aMWU.IsNull())
3403           continue;
3404       
3405         aVal = aMWU->ValueComponent();
3406         anUnit = aMWU->UnitComponent();
3407         if (anUnit.IsNull()) continue;
3408         if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
3409         NU = anUnit.NamedUnit();
3410         anUnitCtx.ComputeFactors(NU);
3411         if (aMWU->IsKind(STANDARD_TYPE(StepBasic_LengthMeasureWithUnit)) ||
3412           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI)))
3413         {
3414           aVal = aVal * anUnitCtx.LengthFactor();
3415         }
3416         else if (aMWU->IsKind(STANDARD_TYPE(StepBasic_PlaneAngleMeasureWithUnit)) ||
3417           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI)))
3418         {
3419           convertAngleValue(anUnitCtx, aVal);
3420         }
3421         aDim2 = Abs(aVal);
3422       }
3423       else
3424       {
3425         // class of tolerance
3426         aLAF = aTMD.LimitsAndFits();
3427       }
3428     }
3429   }
3430
3431   if (aDim1 < 0) return;
3432
3433   if (aDim2 < 0)
3434     aDimObj->SetValue(aDim1);
3435   else if (aDim3 < 0)
3436   {
3437     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1, 2);
3438     anArr->SetValue(1, aDim1);
3439     anArr->SetValue(2, aDim2);
3440     aDimObj->SetValues(anArr);
3441   }
3442   else
3443   {
3444     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1, 3);
3445     if (!isPlusMinusTolerance)
3446     {
3447       aDim2 = aDim1 - aDim2;
3448       aDim3 = aDim3 - aDim1;
3449     }
3450     anArr->SetValue(1, aDim1);
3451     anArr->SetValue(2, aDim2);
3452     anArr->SetValue(3, aDim3);
3453     aDimObj->SetValues(anArr);
3454   }
3455   if (!aTQ.IsNull())
3456   {
3457     XCAFDimTolObjects_DimensionQualifier aQ;
3458     if (STEPCAFControl_GDTProperty::GetDimQualifierType(aTQ->Name(), aQ))
3459     {
3460       aDimObj->SetQualifier(aQ);
3461     }
3462   }
3463
3464   if (!aVFTQ.IsNull())
3465   {
3466     //A typical value would be 'NR2 2.2'
3467     TCollection_HAsciiString aFormat = aVFTQ->FormatType();
3468     Standard_Integer i = aFormat.Location(1, ' ', 1, aFormat.Length());
3469     aFormat.SubString(i + 1, i + 1)->IntegerValue();
3470     aDimObj->SetNbOfDecimalPlaces(aFormat.SubString(i + 1, i + 1)->IntegerValue(),
3471       aFormat.SubString(i + 3, i + 3)->IntegerValue());
3472   }
3473
3474   if (!aLAF.IsNull())
3475   {
3476     //get class of tolerance
3477     Standard_Boolean aHolle = Standard_False;
3478     XCAFDimTolObjects_DimensionFormVariance aFV = XCAFDimTolObjects_DimensionFormVariance_None;
3479     XCAFDimTolObjects_DimensionGrade aG = XCAFDimTolObjects_DimensionGrade_IT01;
3480     STEPCAFControl_GDTProperty::GetDimClassOfTolerance(aLAF, aHolle, aFV, aG);
3481     aDimObj->SetClassOfTolerance(aHolle, aFV, aG);
3482   }
3483
3484   if (!aCRI.IsNull() && !aCRI->ItemElement().IsNull() && aCRI->ItemElement()->Length() > 0)
3485   {
3486     //get modifiers
3487     XCAFDimTolObjects_DimensionModifiersSequence aModifiers;
3488     STEPCAFControl_GDTProperty::GetDimModifiers(aCRI, aModifiers);
3489     if (aModifiers.Length() > 0)
3490       aDimObj->SetModifiers(aModifiers);
3491   }
3492
3493   Handle(TCollection_HAsciiString) aName;
3494   if (!aDimSize.IsNull())
3495   {
3496     aName = aDimSize->Name();
3497   }
3498   else
3499   {
3500     aName = aDimLocation->Name();
3501   }
3502   XCAFDimTolObjects_DimensionType aType = XCAFDimTolObjects_DimensionType_Location_None;
3503   if (!STEPCAFControl_GDTProperty::GetDimType(aName, aType))
3504   {
3505     if (!aDimSize.IsNull())
3506     {
3507       Handle(StepShape_AngularSize) anAngSize =
3508         Handle(StepShape_AngularSize)::DownCast(aDimSize);
3509       if (!anAngSize.IsNull())
3510       {
3511         //get qualifier for angular value
3512         aType = XCAFDimTolObjects_DimensionType_Size_Angular;
3513         if (anAngSize->AngleSelection() == StepShape_Equal)
3514           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3515         else if (anAngSize->AngleSelection() == StepShape_Large)
3516           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3517         else if (anAngSize->AngleSelection() == StepShape_Small)
3518           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3519       }
3520     }
3521     else
3522     {
3523       Handle(StepShape_AngularLocation) anAngLoc =
3524         Handle(StepShape_AngularLocation)::DownCast(aDimLocation);
3525       if (!anAngLoc.IsNull())
3526       {
3527         //get qualifier for angular value
3528         aType = XCAFDimTolObjects_DimensionType_Location_Angular;
3529         if (anAngLoc->AngleSelection() == StepShape_Equal)
3530           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3531         else if (anAngLoc->AngleSelection() == StepShape_Large)
3532           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3533         else if (anAngLoc->AngleSelection() == StepShape_Small)
3534           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3535       }
3536     }
3537     if (aType == XCAFDimTolObjects_DimensionType_Location_None)
3538     {
3539       Handle(StepRepr_ShapeAspect) aPSA;
3540       if (!aDimSize.IsNull())
3541       {
3542         Handle(StepShape_DimensionalSizeWithPath) aDimSizeWithPath =
3543           Handle(StepShape_DimensionalSizeWithPath)::DownCast(aDimSize);
3544         if (!aDimSizeWithPath.IsNull())
3545         {
3546           aType = XCAFDimTolObjects_DimensionType_Size_WithPath;
3547           aPSA = aDimSizeWithPath->Path();
3548         }
3549       }
3550       else
3551       {
3552         Handle(StepShape_DimensionalLocationWithPath) aDimLocWithPath =
3553           Handle(StepShape_DimensionalLocationWithPath)::DownCast(aDimLocation);
3554         if (!aDimLocWithPath.IsNull())
3555         {
3556           aType = XCAFDimTolObjects_DimensionType_Location_WithPath;
3557           aPSA = aDimLocWithPath->Path();
3558         }
3559       }
3560
3561       if (!aPSA.IsNull())
3562       {
3563         //for DimensionalLocationWithPath
3564         Handle(StepGeom_GeometricRepresentationItem) aGRI;
3565         Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
3566         Interface_EntityIterator anIterDSWP = aGraph.Sharings(aPSA);
3567         for (anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
3568           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
3569         }
3570         if (aPGISU.IsNull()) return;
3571         if (aPGISU->NbIdentifiedItem() > 0) {
3572           aGRI = Handle(StepGeom_GeometricRepresentationItem)::DownCast(aPGISU->IdentifiedItemValue(1));
3573         }
3574         if (aGRI.IsNull()) return;
3575         Handle(StepRepr_RepresentationItem) aPRI;
3576         Interface_EntityIterator anIterGRI = aGraph.Sharings(aGRI);
3577         for (anIterGRI.Start(); anIterGRI.More() && aPGISU.IsNull(); anIterGRI.Next()) {
3578           aPRI = Handle(StepRepr_RepresentationItem)::DownCast(anIterGRI.Value());
3579         }
3580         Standard_Integer anIndex = FindShapeIndexForDGT(aPRI, theWS);
3581         TopoDS_Edge aSh;
3582         if (anIndex > 0) {
3583           Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
3584           aSh = TopoDS::Edge(TransferBRep::ShapeResult(aBinder));
3585         }
3586         if (aSh.IsNull()) return;
3587         aDimObj->SetPath(aSh);
3588       }
3589       else if (!anAP.IsNull())
3590       {
3591         if (anAP->Name()->String().IsEqual("orientation") && !anAP->Axis().IsNull())
3592         {
3593           //for Oriented Dimensional Location
3594           Handle(TColStd_HArray1OfReal) aDirArr = anAP->RefDirection()->DirectionRatios();
3595           gp_Dir aDir;
3596           if (!aDirArr.IsNull() && aDirArr->Length() > 2)
3597           {
3598             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower() + 1, aDirArr->Lower() + 2);
3599             aDimObj->SetDirection(aDir);
3600           }
3601           else if (aDirArr->Length() > 1)
3602           {
3603             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower() + 1, 0);
3604             aDimObj->SetDirection(aDir);
3605           }
3606         }
3607       }
3608     }
3609   }
3610   aDimObj->SetType(aType);
3611
3612
3613   if (!aDimObj.IsNull())
3614   {
3615
3616     Handle(XCAFDoc_Dimension) aDim;
3617
3618     if (aDimL.FindAttribute(XCAFDoc_Dimension::GetID(), aDim))
3619     {
3620       readAnnotation(aTR, theEnt, aDimObj);
3621       readConnectionPoints(aTR, theEnt, aDimObj);
3622       aDim->SetObject(aDimObj);
3623     }
3624   }
3625 }
3626
3627 //=======================================================================
3628 //function : getTolType
3629 //purpose  : 
3630 //=======================================================================
3631 static Standard_Boolean getTolType(const Handle(Standard_Transient)& theEnt,
3632   XCAFDimTolObjects_GeomToleranceType& theType)
3633 {
3634   if (theEnt.IsNull() || !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
3635     return Standard_False;
3636   theType = XCAFDimTolObjects_GeomToleranceType_None;
3637   if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRef)))
3638   {
3639     Handle(StepDimTol_GeoTolAndGeoTolWthDatRef) anE = Handle(StepDimTol_GeoTolAndGeoTolWthDatRef)::DownCast(theEnt);
3640     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3641   }
3642   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3643   {
3644     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) anE =
3645       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)::DownCast(theEnt);
3646     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3647   }
3648   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)))
3649   {
3650     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod) anE =
3651       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)::DownCast(theEnt);
3652     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3653   }
3654   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3655   {
3656     Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) anE =
3657       Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)::DownCast(theEnt);
3658     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3659   }
3660   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMod)))
3661   {
3662     Handle(StepDimTol_GeoTolAndGeoTolWthMod) anE =
3663       Handle(StepDimTol_GeoTolAndGeoTolWthMod)::DownCast(theEnt);
3664     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3665   }
3666   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol)))
3667   {
3668     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol) anE =
3669       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol)::DownCast(theEnt);
3670     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3671   }
3672   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))
3673   {
3674     theType = XCAFDimTolObjects_GeomToleranceType_Angularity;
3675   }
3676   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))
3677   {
3678     theType = XCAFDimTolObjects_GeomToleranceType_CircularRunout;
3679   }
3680   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance)))
3681   {
3682     theType = XCAFDimTolObjects_GeomToleranceType_CircularityOrRoundness;
3683   }
3684   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))
3685   {
3686     theType = XCAFDimTolObjects_GeomToleranceType_Coaxiality;
3687   }
3688   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))
3689   {
3690     theType = XCAFDimTolObjects_GeomToleranceType_Concentricity;
3691   }
3692   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance)))
3693   {
3694     theType = XCAFDimTolObjects_GeomToleranceType_Cylindricity;
3695   }
3696   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance)))
3697   {
3698     theType = XCAFDimTolObjects_GeomToleranceType_Flatness;
3699   }
3700   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))
3701   {
3702     theType = XCAFDimTolObjects_GeomToleranceType_Parallelism;
3703   }
3704   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance)))
3705   {
3706     theType = XCAFDimTolObjects_GeomToleranceType_Perpendicularity;
3707   }
3708   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance)) ||
3709     theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)))
3710   {
3711     theType = XCAFDimTolObjects_GeomToleranceType_Position;
3712   }
3713   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance)))
3714   {
3715     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfLine;
3716   }
3717   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance)))
3718   {
3719     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfSurface;
3720   }
3721   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance)))
3722   {
3723     theType = XCAFDimTolObjects_GeomToleranceType_Straightness;
3724   }
3725   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))
3726   {
3727     theType = XCAFDimTolObjects_GeomToleranceType_Symmetry;
3728   }
3729   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))
3730   {
3731     theType = XCAFDimTolObjects_GeomToleranceType_TotalRunout;
3732   }
3733   return Standard_True;
3734 }
3735 //=======================================================================
3736 //function : setGeomTolObjectToXCAF
3737 //purpose  : 
3738 //=======================================================================
3739 static void setGeomTolObjectToXCAF(const Handle(Standard_Transient)& theEnt,
3740   const TDF_Label& theTolL,
3741   const Handle(TDocStd_Document)& theDoc,
3742   const Handle(XSControl_WorkSession)& theWS)
3743 {
3744   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
3745   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
3746   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
3747   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
3748   const Interface_Graph& aGraph = aTP->Graph();
3749   Handle(XCAFDoc_GeomTolerance) aGTol;
3750   if (!theTolL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aGTol))
3751   {
3752     return;
3753   }
3754   Handle(XCAFDimTolObjects_GeomToleranceObject) aTolObj = aGTol->GetObject();
3755   Handle(StepDimTol_GeometricTolerance) aTolEnt = Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
3756
3757   XCAFDimTolObjects_GeomToleranceType aType = XCAFDimTolObjects_GeomToleranceType_None;
3758   getTolType(theEnt, aType);
3759   aTolObj->SetType(aType);
3760   if (!aTolEnt->Magnitude().IsNull()) {
3761     //get value
3762     Standard_Real aVal = aTolEnt->Magnitude()->ValueComponent();
3763     StepBasic_Unit anUnit = aTolEnt->Magnitude()->UnitComponent();
3764     if (anUnit.IsNull()) return;
3765     if (!(anUnit.CaseNum(anUnit.Value()) == 1)) return;
3766     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3767     STEPConstruct_UnitContext anUnitCtx;
3768     anUnitCtx.ComputeFactors(NU);
3769     aVal = aVal * anUnitCtx.LengthFactor();
3770     aTolObj->SetValue(aVal);
3771   }
3772   //get modifiers
3773   XCAFDimTolObjects_GeomToleranceTypeValue aTypeV = XCAFDimTolObjects_GeomToleranceTypeValue_None;
3774   Interface_EntityIterator anIter = aGraph.Sharings(aTolEnt);
3775   for (anIter.Start(); anIter.More(); anIter.Next()) {
3776     if (anIter.Value()->IsKind(STANDARD_TYPE(StepDimTol_ToleranceZone))) {
3777       Handle(StepDimTol_ToleranceZoneForm) aForm
3778         = Handle(StepDimTol_ToleranceZone)::DownCast(anIter.Value())->Form();
3779       STEPCAFControl_GDTProperty::GetTolValueType(aForm->Name(), aTypeV);
3780       Interface_EntityIterator anIt = aGraph.Sharings(anIter.Value());
3781       for (anIt.Start(); anIt.More(); anIt.Next()) {
3782         if (anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_ProjectedZoneDefinition))) {
3783           Handle(StepDimTol_ProjectedZoneDefinition) aPZone
3784             = Handle(StepDimTol_ProjectedZoneDefinition)::DownCast(anIt.Value());
3785           if (!aPZone->ProjectionLength().IsNull())
3786           {
3787             Standard_Real aVal = aPZone->ProjectionLength()->ValueComponent();
3788             StepBasic_Unit anUnit = aPZone->ProjectionLength()->UnitComponent();
3789             if (anUnit.IsNull()) return;
3790             if (!(anUnit.CaseNum(anUnit.Value()) == 1)) return;
3791             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3792             STEPConstruct_UnitContext anUnitCtx;
3793             anUnitCtx.ComputeFactors(NU);
3794             aVal = aVal * anUnitCtx.LengthFactor();
3795             aTolObj->SetValueOfZoneModifier(aVal);
3796             aTolObj->SetZoneModifier(XCAFDimTolObjects_GeomToleranceZoneModif_Projected);
3797           }
3798         }
3799         else if (anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_RunoutZoneDefinition)))
3800         {
3801           Handle(StepDimTol_RunoutZoneDefinition) aRZone
3802             = Handle(StepDimTol_RunoutZoneDefinition)::DownCast(anIt.Value());
3803           if (!aRZone->Orientation().IsNull())
3804           {
3805             Standard_Real aVal = aRZone->Orientation()->Angle()->ValueComponent();
3806             StepBasic_Unit anUnit = aRZone->Orientation()->Angle()->UnitComponent();
3807             if (anUnit.IsNull()) continue;
3808             if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
3809             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3810             STEPConstruct_UnitContext anUnitCtx;
3811             anUnitCtx.ComputeFactors(NU);
3812             convertAngleValue(anUnitCtx, aVal);
3813             aTolObj->SetValueOfZoneModifier(aVal);
3814             aTolObj->SetZoneModifier(XCAFDimTolObjects_GeomToleranceZoneModif_Runout);
3815           }
3816         }
3817       }
3818       aTolObj->SetTypeOfValue(aTypeV);
3819     }
3820   }
3821   Handle(StepDimTol_HArray1OfGeometricToleranceModifier) aModifiers;
3822   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithModifiers)))
3823   {
3824     aModifiers = Handle(StepDimTol_GeometricToleranceWithModifiers)::DownCast(aTolEnt)->Modifiers();
3825   }
3826   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)))
3827   {
3828     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)
3829       ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3830   }
3831   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMod)))
3832   {
3833     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthMod)
3834       ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3835   }
3836   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3837   {
3838     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)
3839       ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3840   }
3841   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3842   {
3843     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)
3844       ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3845   }
3846   if (!aModifiers.IsNull())
3847   {
3848     for (Standard_Integer i = aModifiers->Lower(); i <= aModifiers->Upper(); i++)
3849     {
3850       if (aModifiers->Value(i) == StepDimTol_GTMLeastMaterialRequirement)
3851         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_L);
3852       else if (aModifiers->Value(i) == StepDimTol_GTMMaximumMaterialRequirement)
3853         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_M);
3854       else
3855         aTolObj->AddModifier((XCAFDimTolObjects_GeomToleranceModif)aModifiers->Value(i));
3856     }
3857   }
3858   Standard_Real aVal = 0;
3859   StepBasic_Unit anUnit;
3860   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithMaximumTolerance)))
3861   {
3862     Handle(StepDimTol_GeometricToleranceWithMaximumTolerance) aMax = Handle(StepDimTol_GeometricToleranceWithMaximumTolerance)::DownCast(aTolEnt);
3863     aVal = aMax->MaximumUpperTolerance()->ValueComponent();
3864     anUnit = aMax->MaximumUpperTolerance()->UnitComponent();
3865   }
3866   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3867   {
3868     Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) aMax =
3869       Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)::DownCast(aTolEnt);
3870     aVal = aMax->GetMaxTolerance()->ValueComponent();
3871     anUnit = aMax->GetMaxTolerance()->UnitComponent();
3872   }
3873   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3874   {
3875     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) aMax =
3876       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)::DownCast(aTolEnt);
3877     aVal = aMax->GetMaxTolerance()->ValueComponent();
3878     anUnit = aMax->GetMaxTolerance()->UnitComponent();
3879   }
3880   if (!anUnit.IsNull() && (anUnit.CaseNum(anUnit.Value()) == 1))
3881   {
3882     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3883     STEPConstruct_UnitContext anUnitCtx;
3884     anUnitCtx.ComputeFactors(NU);
3885     convertAngleValue(anUnitCtx, aVal);
3886     aTolObj->SetMaxValueModifier(aVal);
3887   }
3888
3889   readAnnotation(aTR, theEnt, aTolObj);
3890   aGTol->SetObject(aTolObj);
3891 }
3892
3893 //=======================================================================
3894 //function : ReadGDTs
3895 //purpose  : 
3896 //=======================================================================
3897
3898 Standard_Boolean STEPCAFControl_Reader::ReadGDTs(const Handle(XSControl_WorkSession)& theWS,
3899   Handle(TDocStd_Document)& theDoc)
3900 {
3901   const Handle(Interface_InterfaceModel) &aModel = theWS->Model();
3902   const Interface_Graph& aGraph = theWS->Graph();
3903   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
3904   Handle(StepData_StepModel) aSM = Handle(StepData_StepModel)::DownCast(aModel);
3905   Interface_EntityIterator anI = aSM->Header();
3906   Handle(HeaderSection_FileSchema) aH;
3907   for (anI.Start(); anI.More() && aH.IsNull();anI.Next())
3908     aH = Handle(HeaderSection_FileSchema)::DownCast(anI.Value());
3909   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
3910   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
3911   if (aDGTTool.IsNull()) return Standard_False;
3912
3913   Standard_Integer nb = aModel->NbEntities();
3914   for (Standard_Integer i = 1; i <= nb; i++) {
3915     Handle(Standard_Transient) anEnt = aModel->Value(i);
3916     if (anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) ||
3917       anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
3918       anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3919       TDF_Label aGDTL = createGDTObjectInXCAF(anEnt, theDoc, theWS);
3920       if (!aGDTL.IsNull()) {
3921         if (anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3922           setGeomTolObjectToXCAF(anEnt, aGDTL, theDoc, theWS);
3923         }
3924         else {
3925           setDimObjectToXCAF(anEnt, aGDTL, theDoc, theWS);
3926         }
3927       }
3928     }
3929     else if (anEnt->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout)) ||
3930       anEnt->IsKind(STANDARD_TYPE(StepVisual_AnnotationOccurrence)))
3931     {
3932       // Protection against import presentation twice
3933       Handle(StepVisual_DraughtingCallout) aDC;
3934       for (Interface_EntityIterator anIter = aGraph.Sharings(anEnt); anIter.More() && aDC.IsNull(); anIter.Next()) {
3935         aDC = Handle(StepVisual_DraughtingCallout)::DownCast(anIter.Value());
3936       }
3937       if (!aDC.IsNull())
3938         continue;
3939       // Read presentations for PMIs without semantic data.
3940       Handle(StepAP242_DraughtingModelItemAssociation) aDMIA;
3941       TDF_LabelSequence aShapesL;
3942       for (Interface_EntityIterator anIter = aGraph.Sharings(anEnt); anIter.More() && aDMIA.IsNull(); anIter.Next()) {
3943         aDMIA = Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(anIter.Value());
3944       }
3945       if (!aDMIA.IsNull()) {
3946         // Check entity, skip all, attached to GDTs
3947         Handle(StepRepr_ShapeAspect) aDefinition = aDMIA->Definition().ShapeAspect();
3948         if (!aDefinition.IsNull()) {
3949           Standard_Boolean isConnectedToGDT = Standard_False;
3950           // Skip if definition is a datum
3951           if (aDefinition->IsKind(STANDARD_TYPE(StepDimTol_Datum)) ||
3952             aDefinition->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)) ||
3953             aDefinition->IsKind(STANDARD_TYPE(StepDimTol_DatumFeature)) ||
3954             aDefinition->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp))) {
3955             isConnectedToGDT = Standard_True;
3956           }
3957           // Skip if any GDT is applied to definition
3958           for (Interface_EntityIterator anIter = aGraph.Sharings(aDefinition); anIter.More() && !isConnectedToGDT; anIter.Next()) {
3959             if (anIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) ||
3960               anIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
3961               anIter.Value()->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3962               isConnectedToGDT = Standard_True;
3963               continue;
3964             }
3965             Handle(StepRepr_ShapeAspectRelationship) aSAR = Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIter.Value());
3966             if (!aSAR.IsNull()) {
3967               Handle(StepRepr_ShapeAspect) aSA = aSAR->RelatedShapeAspect();
3968               if (!aSA.IsNull()) {
3969                 if (aSA->IsKind(STANDARD_TYPE(StepDimTol_Datum)) ||
3970                   aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)) ||
3971                   aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumFeature)) ||
3972                   aSA->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp))) {
3973                   isConnectedToGDT = Standard_True;
3974                 }
3975                 for (Interface_EntityIterator aDimIter = aGraph.Sharings(aSA); aDimIter.More() && !isConnectedToGDT; aDimIter.Next()) {
3976                   if (aDimIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) ||
3977                     aDimIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
3978                     aDimIter.Value()->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3979                     isConnectedToGDT = Standard_True;
3980                     continue;
3981                   }
3982                 }
3983               }
3984             }
3985           }
3986           if (isConnectedToGDT)
3987             continue;
3988         }
3989         else if (aDMIA->Definition().PropertyDefinition().IsNull())
3990           continue;
3991
3992         // Get shapes
3993         NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
3994         collectShapeAspect(aDefinition, theWS, aSAs);
3995         for (Standard_Integer aSAIt = 1; aSAIt <= aSAs.Length(); aSAIt++) {
3996           Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
3997           for (Interface_EntityIterator anIter = aGraph.Sharings(aSAs.Value(aSAIt)); anIter.More() && aGISU.IsNull(); anIter.Next())
3998             aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIter.Value());
3999           if (aGISU.IsNull())
4000             continue;
4001           for (Standard_Integer anItemIt = 1; anItemIt <= aGISU->NbIdentifiedItem(); anItemIt++) {
4002             TDF_Label aLabel = getShapeLabel(aGISU->IdentifiedItemValue(anItemIt), theWS, XCAFDoc_DocumentTool::ShapeTool(theDoc->Main()));
4003             if (!aLabel.IsNull())
4004               aShapesL.Append(aLabel);
4005           }
4006         }
4007       }
4008       Standard_Boolean isCommonLabel = (aShapesL.Length() == 0);
4009
4010       // Calculate unit
4011       Standard_Real aFact = 1.0;
4012       if (!aDMIA.IsNull())
4013       {
4014         XSAlgo::AlgoContainer()->PrepareForTransfer();
4015         STEPControl_ActorRead anActor;
4016         Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
4017         anActor.PrepareUnits(aDMIA->UsedRepresentation(), aTP);
4018         aFact = UnitsMethods::LengthFactor();
4019       }
4020
4021       // Presentation
4022       TopoDS_Shape aPresentation;
4023       Handle(TCollection_HAsciiString) aPresentName;
4024       Bnd_Box aBox;
4025       if (!readPMIPresentation(anEnt, aTR, aFact, aPresentation, aPresentName, aBox))
4026         continue;
4027       // Annotation plane
4028       Handle(StepVisual_AnnotationPlane) anAnPlane;
4029       for (Interface_EntityIterator anIter = aGraph.Sharings(anEnt); anIter.More() && anAnPlane.IsNull(); anIter.Next())
4030         anAnPlane = Handle(StepVisual_AnnotationPlane)::DownCast(anIter.Value());
4031
4032       // Set object to XCAF
4033       TDF_Label aGDTL = aDGTTool->AddDimension();
4034       myGDTMap.Bind(anEnt, aGDTL);
4035       aDGTTool->Lock(aGDTL);
4036       Handle(XCAFDimTolObjects_DimensionObject) aDimObj = new XCAFDimTolObjects_DimensionObject();
4037       Handle(XCAFDoc_Dimension) aDim = XCAFDoc_Dimension::Set(aGDTL);
4038       TCollection_AsciiString aStr("DGT:");
4039       if (isCommonLabel) {
4040         aStr.AssignCat("Common_label");
4041         aDimObj->SetType(XCAFDimTolObjects_DimensionType_CommonLabel);
4042       }
4043       else {
4044         aStr.AssignCat("Dimension");
4045         aDimObj->SetType(XCAFDimTolObjects_DimensionType_DimensionPresentation);
4046       }
4047       TDataStd_Name::Set(aGDTL, aStr);
4048       TDF_LabelSequence anEmptySeq2;
4049       aDGTTool->SetDimension(aShapesL, anEmptySeq2, aGDTL);
4050       gp_Ax2 aPlaneAxes;
4051       if (!anAnPlane.IsNull()) {
4052         if (readAnnotationPlane(anAnPlane, aPlaneAxes))
4053           aDimObj->SetPlane(aPlaneAxes);
4054       }
4055       aDimObj->SetPresentation(aPresentation, aPresentName);
4056       aDim->SetObject(aDimObj);
4057     }
4058   }
4059   return Standard_True;
4060 }
4061
4062
4063 //=======================================================================
4064 //function : FindSolidForPDS
4065 //purpose  : auxilary
4066 //=======================================================================
4067
4068 static Handle(StepShape_SolidModel) FindSolidForPDS(const Handle(StepRepr_ProductDefinitionShape) &PDS,
4069   const Interface_Graph &graph)
4070 {
4071   Handle(StepShape_SolidModel) SM;
4072   Interface_EntityIterator subs = graph.Sharings(PDS);
4073   Handle(StepShape_ShapeRepresentation) SR;
4074   for (subs.Start(); subs.More() && SM.IsNull(); subs.Next()) {
4075     Handle(StepShape_ShapeDefinitionRepresentation) SDR =
4076       Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
4077     if (SDR.IsNull()) continue;
4078     SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
4079     if (SR.IsNull()) continue;
4080     for (Standard_Integer i = 1; i <= SR->NbItems() && SM.IsNull(); i++) {
4081       SM = Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(i));
4082     }
4083     if (SM.IsNull()) {
4084       Interface_EntityIterator subs1 = graph.Sharings(SR);
4085       for (subs1.Start(); subs1.More() && SM.IsNull(); subs1.Next()) {
4086         Handle(StepRepr_RepresentationRelationship) RR =
4087           Handle(StepRepr_RepresentationRelationship)::DownCast(subs1.Value());
4088         if (RR.IsNull()) continue;
4089         Handle(StepShape_ShapeRepresentation) SR2;
4090         if (RR->Rep1() == SR) SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep2());
4091         else SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep1());
4092         if (SR2.IsNull()) continue;
4093         for (Standard_Integer i2 = 1; i2 <= SR2->NbItems() && SM.IsNull(); i2++) {
4094           SM = Handle(StepShape_SolidModel)::DownCast(SR2->ItemsValue(i2));
4095         }
4096       }
4097     }
4098   }
4099   return SM;
4100 }
4101
4102
4103 //=======================================================================
4104 //function : ReadMaterials
4105 //purpose  : 
4106 //=======================================================================
4107
4108 Standard_Boolean STEPCAFControl_Reader::ReadMaterials(const Handle(XSControl_WorkSession) &WS,
4109   Handle(TDocStd_Document)& Doc,
4110   const Handle(TColStd_HSequenceOfTransient) &SeqPDS) const
4111 {
4112   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
4113   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
4114   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool(Doc->Main());
4115   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool(Doc->Main());
4116   if (MatTool.IsNull()) return Standard_False;
4117
4118   const Interface_Graph& graph = TP->Graph();
4119   for (Standard_Integer i = 1; i <= SeqPDS->Length(); i++) {
4120     Handle(StepRepr_ProductDefinitionShape) PDS =
4121       Handle(StepRepr_ProductDefinitionShape)::DownCast(SeqPDS->Value(i));
4122     if (PDS.IsNull())
4123       continue;
4124     Handle(StepBasic_ProductDefinition) aProdDef = PDS->Definition().ProductDefinition();
4125     if (aProdDef.IsNull())
4126       continue;
4127     Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString("");
4128     Handle(TCollection_HAsciiString) aDescription = new TCollection_HAsciiString("");
4129     Handle(TCollection_HAsciiString) aDensName = new TCollection_HAsciiString("");
4130     Handle(TCollection_HAsciiString) aDensValType = new TCollection_HAsciiString("");
4131     Standard_Real aDensity = 0;
4132     Interface_EntityIterator subs = graph.Sharings(aProdDef);
4133     for (subs.Start(); subs.More(); subs.Next()) {
4134       Handle(StepRepr_PropertyDefinition) PropD =
4135         Handle(StepRepr_PropertyDefinition)::DownCast(subs.Value());
4136       if (PropD.IsNull()) continue;
4137       Interface_EntityIterator subs1 = graph.Sharings(PropD);
4138       for (subs1.Start(); subs1.More(); subs1.Next()) {
4139         Handle(StepRepr_PropertyDefinitionRepresentation) PDR =
4140           Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast(subs1.Value());
4141         if (PDR.IsNull()) continue;
4142         Handle(StepRepr_Representation) Repr = PDR->UsedRepresentation();
4143         if (Repr.IsNull()) continue;
4144         Standard_Integer ir;
4145         for (ir = 1; ir <= Repr->NbItems(); ir++) {
4146           Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(ir);
4147           if (RI.IsNull()) continue;
4148           if (RI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
4149             // find name and description for material
4150             Handle(StepRepr_DescriptiveRepresentationItem) DRI =
4151               Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(RI);
4152             aName = DRI->Name();
4153
4154             aDescription = DRI->Description();
4155             if (aName.IsNull())
4156               aName = aDescription;
4157           }
4158           if (RI->IsKind(STANDARD_TYPE(StepRepr_MeasureRepresentationItem))) {
4159             // try to find density for material
4160             Handle(StepRepr_MeasureRepresentationItem) MRI =
4161               Handle(StepRepr_MeasureRepresentationItem)::DownCast(RI);
4162             aDensity = MRI->Measure()->ValueComponent();
4163             aDensName = MRI->Name();
4164             aDensValType = new TCollection_HAsciiString(MRI->Measure()->ValueComponentMember()->Name());
4165             StepBasic_Unit aUnit = MRI->Measure()->UnitComponent();
4166             if (!aUnit.IsNull()) {
4167               Handle(StepBasic_DerivedUnit) DU = aUnit.DerivedUnit();
4168               if (DU.IsNull()) continue;
4169               for (Standard_Integer idu = 1; idu <= DU->NbElements(); idu++) {
4170                 Handle(StepBasic_DerivedUnitElement) DUE = DU->ElementsValue(idu);
4171                 Handle(StepBasic_NamedUnit) NU = DUE->Unit();
4172                 if (NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit)) ||
4173                   NU->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit)))
4174                 {
4175                   STEPConstruct_UnitContext anUnitCtx;
4176                   anUnitCtx.ComputeFactors(NU);
4177                   aDensity = aDensity / (anUnitCtx.LengthFactor()*anUnitCtx.LengthFactor()*anUnitCtx.LengthFactor());
4178                   // transfer length value for Density from millimeter to santimeter
4179                   // in order to result density has dimension gram/(sm*sm*sm)
4180                   aDensity = aDensity*1000. / (UnitsMethods::GetCasCadeLengthUnit()
4181                     * UnitsMethods::GetCasCadeLengthUnit() * UnitsMethods::GetCasCadeLengthUnit());
4182                 }
4183                 if (NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit))) {
4184                   Standard_Real afact = 1.;
4185                   if (GetMassConversionFactor(NU, afact))
4186                   {
4187                     aDensity = aDensity*afact;
4188                   }
4189                 }
4190               }
4191             }
4192           }
4193         }
4194       }
4195     }
4196
4197     if (aName.IsNull() || aName->Length() == 0)
4198       continue;
4199     // find shape label amd create Material link
4200     TopoDS_Shape aSh;
4201     Handle(StepShape_SolidModel) SM = FindSolidForPDS(PDS, graph);
4202     if (!SM.IsNull()) {
4203       Standard_Integer index = TP->MapIndex(SM);
4204       if (index > 0) {
4205         Handle(Transfer_Binder) binder = TP->MapItem(index);
4206         if (!binder.IsNull())
4207           aSh = TransferBRep::ShapeResult(binder);
4208       }
4209     }
4210     if (aSh.IsNull()) continue;
4211     TDF_Label shL;
4212     if (!STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True)) continue;
4213     MatTool->SetMaterial(shL, aName, aDescription, aDensity, aDensName, aDensValType);
4214   }
4215
4216   return Standard_True;
4217 }
4218
4219 //=======================================================================
4220 //function : collectViewShapes
4221 //purpose  : collect all labels of representations in given representation
4222 //=======================================================================
4223
4224 void collectViewShapes(const Handle(XSControl_WorkSession)& theWS,
4225   const Handle(TDocStd_Document)& theDoc,
4226   const Handle(StepRepr_Representation) theRepr,
4227   TDF_LabelSequence& theShapes)
4228 {
4229   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
4230   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
4231   const Interface_Graph& aGraph = aTP->Graph();
4232   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
4233   Standard_Integer anIndex = aTP->MapIndex(theRepr);
4234   TopoDS_Shape aSh;
4235   if (anIndex > 0) {
4236     Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
4237     aSh = TransferBRep::ShapeResult(aBinder);
4238   }
4239   if (!aSh.IsNull()) {
4240     TDF_Label aShL;
4241     aSTool->FindShape(aSh, aShL);
4242     if (!aShL.IsNull())
4243       theShapes.Append(aShL);
4244   }
4245   Interface_EntityIterator anIter = aGraph.Sharings(theRepr);
4246   for (; anIter.More(); anIter.Next()) {
4247     if (!anIter.Value()->IsKind(STANDARD_TYPE(StepRepr_RepresentationRelationship)))
4248       continue;
4249     Handle(StepRepr_RepresentationRelationship) aReprRelationship = Handle(StepRepr_RepresentationRelationship)::DownCast(anIter.Value());
4250     if (!aReprRelationship->Rep1().IsNull() && aReprRelationship->Rep1() != theRepr)
4251       collectViewShapes(theWS, theDoc, aReprRelationship->Rep1(), theShapes);
4252   }
4253 }
4254
4255 //=======================================================================
4256 //function : buildClippingPlanes
4257 //purpose  :
4258 //=======================================================================
4259 Handle(TCollection_HAsciiString) buildClippingPlanes(const Handle(StepGeom_GeometricRepresentationItem)& theClippingCameraModel,
4260   TDF_LabelSequence& theClippingPlanes,
4261   const Handle(XCAFDoc_ClippingPlaneTool) theTool)
4262 {
4263   Handle(TCollection_HAsciiString) anExpression = new TCollection_HAsciiString();
4264   NCollection_Sequence<Handle(StepGeom_GeometricRepresentationItem)> aPlanes;
4265   Handle(TCollection_HAsciiString) anOperation = new TCollection_HAsciiString("*");
4266
4267   // Store operands
4268   if (theClippingCameraModel->IsKind(STANDARD_TYPE(StepVisual_CameraModelD3MultiClipping))) {
4269     Handle(StepVisual_CameraModelD3MultiClipping) aCameraModel =
4270       Handle(StepVisual_CameraModelD3MultiClipping)::DownCast(theClippingCameraModel);
4271
4272     if (aCameraModel->ShapeClipping().IsNull())
4273       return anExpression;
4274
4275     // Root of clipping planes tree
4276     if (aCameraModel->ShapeClipping()->Length() == 1) {
4277       Handle(StepVisual_CameraModelD3MultiClippingUnion) aCameraModelUnion =
4278         aCameraModel->ShapeClipping()->Value(1).CameraModelD3MultiClippingUnion();
4279       if (!aCameraModelUnion.IsNull())
4280         return buildClippingPlanes(aCameraModelUnion, theClippingPlanes, theTool);
4281     }
4282     for (Standard_Integer i = 1; i <= aCameraModel->ShapeClipping()->Length(); i++) {
4283       aPlanes.Append(Handle(StepGeom_GeometricRepresentationItem)::DownCast(aCameraModel->ShapeClipping()->Value(i).Value()));
4284     }
4285   }
4286   else if (theClippingCameraModel->IsKind(STANDARD_TYPE(StepVisual_CameraModelD3MultiClippingUnion))) {
4287     Handle(StepVisual_CameraModelD3MultiClippingUnion) aCameraModel =
4288       Handle(StepVisual_CameraModelD3MultiClippingUnion)::DownCast(theClippingCameraModel);
4289     anOperation = new TCollection_HAsciiString("+");
4290     for (Standard_Integer i = 1; i <= aCameraModel->ShapeClipping()->Length(); i++) {
4291       aPlanes.Append(Handle(StepGeom_GeometricRepresentationItem)::DownCast(aCameraModel->ShapeClipping()->Value(i).Value()));
4292     }
4293   }
4294   else if (theClippingCameraModel->IsKind(STANDARD_TYPE(StepVisual_CameraModelD3MultiClippingIntersection))) {
4295     Handle(StepVisual_CameraModelD3MultiClippingIntersection) aCameraModel =
4296       Handle(StepVisual_CameraModelD3MultiClippingIntersection)::DownCast(theClippingCameraModel);
4297     for (Standard_Integer i = 1; i <= aCameraModel->ShapeClipping()->Length(); i++) {
4298       aPlanes.Append(Handle(StepGeom_GeometricRepresentationItem)::DownCast(aCameraModel->ShapeClipping()->Value(i).Value()));
4299     }
4300   }
4301   // Build expression
4302   anExpression->AssignCat("(");
4303   for (Standard_Integer i = 1; i <= aPlanes.Length(); i++) {
4304     Handle(StepGeom_Plane) aPlaneEnt = Handle(StepGeom_Plane)::DownCast(aPlanes.Value(i));
4305     if (!aPlaneEnt.IsNull()) {
4306       Handle(Geom_Plane) aPlane = StepToGeom::MakePlane(aPlaneEnt);
4307       if (!aPlane.IsNull()) {
4308         TDF_Label aPlaneL = theTool->AddClippingPlane(aPlane->Pln(), aPlaneEnt->Name());
4309         theClippingPlanes.Append(aPlaneL);
4310         TCollection_AsciiString anEntry;
4311         TDF_Tool::Entry(aPlaneL, anEntry);
4312         anExpression->AssignCat(new TCollection_HAsciiString(anEntry));
4313       }
4314     }
4315     else {
4316       anExpression->AssignCat(buildClippingPlanes(aPlanes.Value(i), theClippingPlanes, theTool));
4317     }
4318     anExpression->AssignCat(anOperation);
4319   }
4320   // Insert brace instead of operation after last operand.
4321   anExpression->SetValue(anExpression->Length(), ')');
4322   return anExpression;
4323 }
4324
4325
4326 //=======================================================================
4327 //function : ReadViews
4328 //purpose  :
4329 //=======================================================================
4330 Standard_Boolean STEPCAFControl_Reader::ReadViews(const Handle(XSControl_WorkSession)& theWS, Handle(TDocStd_Document)& theDoc) const
4331 {
4332   const Handle(Interface_InterfaceModel) &aModel = theWS->Model();
4333   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
4334   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
4335   Handle(XCAFDoc_ViewTool) aViewTool = XCAFDoc_DocumentTool::ViewTool(theDoc->Main());
4336   if (aDGTTool.IsNull()) return Standard_False;
4337
4338   Standard_Integer nb = aModel->NbEntities();
4339   for (Standard_Integer i = 1; i <= nb; i++) {
4340     Handle(Standard_Transient) anEnt = aModel->Value(i);
4341     if (!anEnt->IsKind(STANDARD_TYPE(StepVisual_CameraModelD3)))
4342       continue;
4343     Handle(XCAFView_Object) anObj = new XCAFView_Object();
4344     // Import attributes of view
4345     Handle(StepVisual_CameraModelD3) aCameraModel = Handle(StepVisual_CameraModelD3)::DownCast(anEnt);
4346
4347     const Handle(XSControl_TransferReader)& aTR = theWS->TransferReader();
4348     Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
4349     const Interface_Graph& aGraph = aTP->Graph();
4350     // find the proper DraughtingModel
4351     Interface_EntityIterator subs = aGraph.Sharings(aCameraModel);
4352     Handle(StepVisual_DraughtingModel) aDModel;
4353     for (subs.Start(); subs.More() && aDModel.IsNull(); subs.Next())
4354     {
4355       if (!subs.Value()->IsKind(STANDARD_TYPE(StepVisual_DraughtingModel)))
4356       {
4357         continue;
4358       }
4359       aDModel = Handle(StepVisual_DraughtingModel)::DownCast(subs.Value());
4360     }
4361     if (!aDModel.IsNull())
4362     {
4363       XSAlgo::AlgoContainer()->PrepareForTransfer();
4364       STEPControl_ActorRead anActor;
4365       anActor.PrepareUnits(aDModel, aTP);
4366     }
4367
4368     anObj->SetName(aCameraModel->Name());
4369     Handle(Geom_Axis2Placement) anAxis = StepToGeom::MakeAxis2Placement(aCameraModel->ViewReferenceSystem());
4370     anObj->SetViewDirection(anAxis->Direction());
4371     anObj->SetUpDirection(anAxis->Direction() ^ anAxis->XDirection());
4372     Handle(StepVisual_ViewVolume) aViewVolume = aCameraModel->PerspectiveOfVolume();
4373     XCAFView_ProjectionType aType = XCAFView_ProjectionType_NoCamera;
4374     if (aViewVolume->ProjectionType() == StepVisual_copCentral)
4375       aType = XCAFView_ProjectionType_Central;
4376     else if (aViewVolume->ProjectionType() == StepVisual_copParallel)
4377       aType = XCAFView_ProjectionType_Parallel;
4378     anObj->SetType(aType);
4379     Handle(Geom_CartesianPoint) aPoint = StepToGeom::MakeCartesianPoint(aViewVolume->ProjectionPoint());
4380     anObj->SetProjectionPoint(aPoint->Pnt());
4381     anObj->SetZoomFactor(aViewVolume->ViewPlaneDistance());
4382     anObj->SetWindowHorizontalSize(aViewVolume->ViewWindow()->SizeInX());
4383     anObj->SetWindowVerticalSize(aViewVolume->ViewWindow()->SizeInY());
4384     if (aViewVolume->FrontPlaneClipping())
4385       anObj->SetFrontPlaneDistance(aViewVolume->FrontPlaneDistance());
4386     if (aViewVolume->BackPlaneClipping())
4387       anObj->SetBackPlaneDistance(aViewVolume->BackPlaneDistance());
4388     anObj->SetViewVolumeSidesClipping(aViewVolume->ViewVolumeSidesClipping());
4389     // Clipping plane
4390     Handle(StepVisual_CameraModelD3MultiClipping) aClippingCameraModel =
4391       Handle(StepVisual_CameraModelD3MultiClipping)::DownCast(aCameraModel);
4392     TDF_LabelSequence aClippingPlanes;
4393     if (!aClippingCameraModel.IsNull()) {
4394       Handle(TCollection_HAsciiString) aClippingExpression;
4395       Handle(XCAFDoc_ClippingPlaneTool) aClippingPlaneTool = XCAFDoc_DocumentTool::ClippingPlaneTool(theDoc->Main());
4396       aClippingExpression = buildClippingPlanes(aClippingCameraModel, aClippingPlanes, aClippingPlaneTool);
4397       anObj->SetClippingExpression(aClippingExpression);
4398     }
4399
4400     // Collect shapes and GDTs
4401     if (aDModel.IsNull())
4402       return Standard_False;
4403     TDF_LabelSequence aShapes, aGDTs;
4404     Interface_EntityIterator anIter = aGraph.Shareds(aDModel);
4405     for (; anIter.More(); anIter.Next()) {
4406       if (anIter.Value()->IsKind(STANDARD_TYPE(StepRepr_MappedItem))) {
4407         Handle(StepRepr_MappedItem) anItem = Handle(StepRepr_MappedItem)::DownCast(anIter.Value());
4408         Handle(StepRepr_Representation) aRepr = anItem->MappingSource()->MappedRepresentation();
4409         collectViewShapes(theWS, theDoc, aRepr, aShapes);
4410       }
4411       else if (anIter.Value()->IsKind(STANDARD_TYPE(StepVisual_AnnotationOccurrence)) ||
4412         anIter.Value()->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout))) {
4413         Interface_EntityIterator aDMIAIter = aGraph.Sharings(anIter.Value());
4414         for (; aDMIAIter.More(); aDMIAIter.Next()) {
4415           if (!aDMIAIter.Value()->IsKind(STANDARD_TYPE(StepAP242_DraughtingModelItemAssociation)))
4416             continue;
4417           Handle(StepAP242_DraughtingModelItemAssociation) aDMIA =
4418             Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(aDMIAIter.Value());
4419           TDF_Label aGDTL;
4420           Standard_Boolean isFind = myGDTMap.Find(aDMIA->Definition().Value(), aGDTL);
4421           if (!isFind) {
4422             isFind = myGDTMap.Find(anIter.Value(), aGDTL);
4423           }
4424           if (isFind)
4425             aGDTs.Append(aGDTL);
4426         }
4427       }
4428       else if (anIter.Value()->IsKind(STANDARD_TYPE(StepVisual_AnnotationPlane))) {
4429         Handle(StepVisual_AnnotationPlane) aPlane = Handle(StepVisual_AnnotationPlane)::DownCast(anIter.Value());
4430         for (Standard_Integer j = 1; j <= aPlane->NbElements(); j++) {
4431           Interface_EntityIterator aDMIAIter = aGraph.Sharings(anIter.Value());
4432           for (; aDMIAIter.More(); aDMIAIter.Next()) {
4433             if (!aDMIAIter.Value()->IsKind(STANDARD_TYPE(StepAP242_DraughtingModelItemAssociation)))
4434               continue;
4435             Handle(StepAP242_DraughtingModelItemAssociation) aDMIA =
4436               Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(aDMIAIter.Value());
4437             TDF_Label aGDTL;
4438             Standard_Boolean isFind = myGDTMap.Find(aDMIA->Definition().Value(), aGDTL);
4439             if (isFind)
4440               aGDTs.Append(aGDTL);
4441           }
4442         }
4443       }
4444     }
4445     TDF_Label aViewL = aViewTool->AddView();
4446     Handle(XCAFDoc_View) aView = XCAFDoc_View::Set(aViewL);
4447     aView->SetObject(anObj);
4448     aViewTool->SetView(aShapes, aGDTs, aClippingPlanes, aViewL);
4449     aViewTool->Lock(aViewL);
4450   }
4451   return Standard_True;
4452 }
4453
4454 //=======================================================================
4455 //function : SettleShapeData
4456 //purpose  :
4457 //=======================================================================
4458
4459 TDF_Label STEPCAFControl_Reader::SettleShapeData(const Handle(StepRepr_RepresentationItem)& theItem,
4460   const TDF_Label& theLab,
4461   const Handle(XCAFDoc_ShapeTool)& theShapeTool,
4462   const Handle(Transfer_TransientProcess)& TP) const
4463 {
4464   TDF_Label aResult = theLab;
4465
4466   Handle(TCollection_HAsciiString) hName = theItem->Name();
4467   if (hName.IsNull() || hName->IsEmpty())
4468     return aResult;
4469
4470   Handle(Transfer_Binder) aBinder = TP->Find(theItem);
4471   if (aBinder.IsNull())
4472     return aResult;
4473
4474   TopoDS_Shape aShape = TransferBRep::ShapeResult(aBinder);
4475   if (aShape.IsNull())
4476     return aResult;
4477
4478   // Allocate sub-Label
4479   aResult = theShapeTool->AddSubShape(theLab, aShape);
4480   if (aResult.IsNull())
4481     return aResult;
4482
4483   TCollection_AsciiString aName = hName->String();
4484   TDataStd_Name::Set(aResult, aName);
4485   theShapeTool->SetShape(aResult, aShape);
4486
4487   return aResult;
4488 }
4489
4490 //=======================================================================
4491 //function : collectRepresentationItems
4492 //purpose  : recursive collection of representation items for given representation 
4493 //           with all representations, related to it.
4494 //=======================================================================
4495
4496 void collectRepresentationItems(const Interface_Graph& theGraph,
4497   const Handle(StepShape_ShapeRepresentation)& theRepresentation,
4498   NCollection_Sequence<Handle(StepRepr_RepresentationItem)>& theItems)
4499 {
4500   Handle(StepRepr_HArray1OfRepresentationItem) aReprItems = theRepresentation->Items();
4501   for (Standard_Integer itemIt = aReprItems->Lower(); itemIt <= aReprItems->Upper(); itemIt++)
4502     theItems.Append(aReprItems->Value(itemIt));
4503
4504   Interface_EntityIterator entIt = theGraph.TypedSharings(theRepresentation, STANDARD_TYPE(StepRepr_RepresentationRelationship));
4505   for (entIt.Start(); entIt.More(); entIt.Next())
4506   {
4507     Handle(StepRepr_RepresentationRelationship) aRelationship = Handle(StepRepr_RepresentationRelationship)::DownCast(entIt.Value());
4508     if (aRelationship->Rep1() == theRepresentation)
4509     {
4510       Handle(StepShape_ShapeRepresentation)
4511         aRepr = Handle(StepShape_ShapeRepresentation)::DownCast(aRelationship->Rep2());
4512       if (!aRepr.IsNull())
4513         collectRepresentationItems(theGraph, aRepr, theItems);
4514     }
4515   }
4516 }
4517
4518 //=======================================================================
4519 //function : ExpandSubShapes
4520 //purpose  :
4521 //=======================================================================
4522
4523 void STEPCAFControl_Reader::ExpandSubShapes(const Handle(XCAFDoc_ShapeTool)& ShapeTool,
4524   const XCAFDoc_DataMapOfShapeLabel& ShapeLabelMap,
4525   const STEPCAFControl_DataMapOfShapePD& ShapePDMap) const
4526 {
4527   const Handle(Transfer_TransientProcess)& TP = Reader().WS()->TransferReader()->TransientProcess();
4528   NCollection_DataMap<TopoDS_Shape, Handle(TCollection_HAsciiString)> ShapeNameMap;
4529   TColStd_MapOfTransient aRepItems;
4530
4531   // Read translation control variables
4532   Standard_Boolean doReadSNames = (Interface_Static::IVal("read.stepcaf.subshapes.name") > 0);
4533
4534   if (!doReadSNames)
4535     return;
4536
4537   const Interface_Graph& Graph = Reader().WS()->Graph();
4538
4539   for (STEPCAFControl_DataMapIteratorOfDataMapOfShapePD it(ShapePDMap); it.More(); it.Next())
4540   {
4541     const TopoDS_Shape& aRootShape = it.Key();
4542     const Handle(StepBasic_ProductDefinition)& aPDef = it.Value();
4543     if (aPDef.IsNull())
4544       continue;
4545
4546     // Find SDR by Product
4547     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
4548     Interface_EntityIterator entIt = Graph.TypedSharings(aPDef, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation));
4549     for (entIt.Start(); entIt.More(); entIt.Next())
4550     {
4551       const Handle(Standard_Transient)& aReferer = entIt.Value();
4552       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(aReferer);
4553       if (!aSDR.IsNull())
4554         break;
4555     }
4556
4557     if (aSDR.IsNull())
4558       continue;
4559
4560     // Access shape representation
4561     Handle(StepShape_ShapeRepresentation)
4562       aShapeRepr = Handle(StepShape_ShapeRepresentation)::DownCast(aSDR->UsedRepresentation());
4563
4564     if (aShapeRepr.IsNull())
4565       continue;
4566
4567     // Access representation items
4568     NCollection_Sequence<Handle(StepRepr_RepresentationItem)> aReprItems;
4569     collectRepresentationItems(Graph, aShapeRepr, aReprItems);
4570
4571     if (aReprItems.Length() == 0)
4572       continue;
4573
4574     if (!ShapeLabelMap.IsBound(aRootShape))
4575       continue;
4576
4577     TDF_Label aRootLab = ShapeLabelMap.Find(aRootShape);
4578     // Do not add subshapes to assembly,
4579     // they will be processed with corresponding Shape_Product_Definition of necessary part.
4580     if (ShapeTool->IsAssembly(aRootLab))
4581       continue;
4582
4583     StepRepr_SequenceOfRepresentationItem aMSBSeq;
4584     StepRepr_SequenceOfRepresentationItem aSBSMSeq;
4585
4586     // Iterate over the top level representation items collecting the
4587     // topological containers to expand
4588     for (Standard_Integer i = 1; i <= aReprItems.Length(); ++i)
4589     {
4590       Handle(StepRepr_RepresentationItem) aTRepr = aReprItems.Value(i);
4591       if (aTRepr->IsKind(STANDARD_TYPE(StepShape_ManifoldSolidBrep)))
4592         aMSBSeq.Append(aTRepr);
4593       else if (aTRepr->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel)))
4594         aSBSMSeq.Append(aTRepr);
4595     }
4596
4597     // Insert intermediate OCAF Labels for SOLIDs in case there are more
4598     // than one Manifold Solid BRep in the Shape Representation
4599     Standard_Boolean doInsertSolidLab = (aMSBSeq.Length() > 1);
4600
4601     // Expand Manifold Solid BReps
4602     for (Standard_Integer i = 1; i <= aMSBSeq.Length(); ++i)
4603     {
4604       // Put additional Label for SOLID
4605       if (doInsertSolidLab)
4606         SettleShapeData(aMSBSeq.Value(i), aRootLab, ShapeTool, TP);
4607
4608       ExpandManifoldSolidBrep(aRootLab, aMSBSeq.Value(i), TP, ShapeTool);
4609     }
4610
4611     // Expand Shell-Based Surface Models
4612     for (Standard_Integer i = 1; i <= aSBSMSeq.Length(); ++i)
4613       ExpandSBSM(aRootLab, aSBSMSeq.Value(i), TP, ShapeTool);
4614   }
4615 }
4616
4617 //=======================================================================
4618 //function : ExpandManifoldSolidBrep
4619 //purpose  :
4620 //=======================================================================
4621
4622 void STEPCAFControl_Reader::ExpandManifoldSolidBrep(TDF_Label& ShapeLab,
4623   const Handle(StepRepr_RepresentationItem)& Repr,
4624   const Handle(Transfer_TransientProcess)& TP,
4625   const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
4626 {
4627   // Access outer shell
4628   Handle(StepShape_ManifoldSolidBrep) aMSB = Handle(StepShape_ManifoldSolidBrep)::DownCast(Repr);
4629   Handle(StepShape_ConnectedFaceSet) aShell = aMSB->Outer();
4630
4631   // Expand shell contents to CAF tree
4632   ExpandShell(aShell, ShapeLab, TP, ShapeTool);
4633 }
4634
4635 //=======================================================================
4636 //function : ExpandSBSM
4637 //purpose  :
4638 //=======================================================================
4639
4640 void STEPCAFControl_Reader::ExpandSBSM(TDF_Label& ShapeLab,
4641   const Handle(StepRepr_RepresentationItem)& Repr,
4642   const Handle(Transfer_TransientProcess)& TP,
4643   const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
4644 {
4645   Handle(StepShape_ShellBasedSurfaceModel) aSBSM = Handle(StepShape_ShellBasedSurfaceModel)::DownCast(Repr);
4646
4647   // Access boundary shells
4648   Handle(StepShape_HArray1OfShell) aShells = aSBSM->SbsmBoundary();
4649   for (Standard_Integer s = aShells->Lower(); s <= aShells->Upper(); ++s)
4650   {
4651     const StepShape_Shell& aShell = aShells->Value(s);
4652     Handle(StepShape_ConnectedFaceSet) aCFS;
4653     Handle(StepShape_OpenShell) anOpenShell = aShell.OpenShell();
4654     Handle(StepShape_ClosedShell) aClosedShell = aShell.ClosedShell();
4655
4656     if (!anOpenShell.IsNull())
4657       aCFS = anOpenShell;
4658     else
4659       aCFS = aClosedShell;
4660
4661     ExpandShell(aCFS, ShapeLab, TP, ShapeTool);
4662   }
4663 }
4664
4665 //=======================================================================
4666 //function : ExpandShell
4667 //purpose  :
4668 //=======================================================================
4669
4670 void STEPCAFControl_Reader::ExpandShell(const Handle(StepShape_ConnectedFaceSet)& Shell,
4671   TDF_Label& RootLab,
4672   const Handle(Transfer_TransientProcess)& TP,
4673   const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
4674 {
4675   // Record CAF data
4676   SettleShapeData(Shell, RootLab, ShapeTool, TP);
4677
4678   // Access faces
4679   Handle(StepShape_HArray1OfFace) aFaces = Shell->CfsFaces();
4680   for (Standard_Integer f = aFaces->Lower(); f <= aFaces->Upper(); ++f)
4681   {
4682     const Handle(StepShape_Face)& aFace = aFaces->Value(f);
4683     if (aFace.IsNull())
4684       continue;
4685
4686     // Record CAF data
4687     SettleShapeData(aFace, RootLab, ShapeTool, TP);
4688
4689     // Access face bounds
4690     Handle(StepShape_HArray1OfFaceBound) aWires = aFace->Bounds();
4691     if (aWires.IsNull())
4692       continue;
4693     for (Standard_Integer w = aWires->Lower(); w <= aWires->Upper(); ++w)
4694     {
4695       const Handle(StepShape_Loop)& aWire = aWires->Value(w)->Bound();
4696
4697       // Record CAF data
4698       SettleShapeData(aWire, RootLab, ShapeTool, TP);
4699
4700       // Access wire edges
4701       // Currently only EDGE LOOPs are considered (!)
4702       if (!aWire->IsInstance(STANDARD_TYPE(StepShape_EdgeLoop)))
4703         continue;
4704
4705       // Access edges
4706       Handle(StepShape_EdgeLoop) anEdgeLoop = Handle(StepShape_EdgeLoop)::DownCast(aWire);
4707       Handle(StepShape_HArray1OfOrientedEdge) anEdges = anEdgeLoop->EdgeList();
4708       for (Standard_Integer e = anEdges->Lower(); e <= anEdges->Upper(); ++e)
4709       {
4710         Handle(StepShape_OrientedEdge) anOrientedEdge = anEdges->Value(e);
4711         if (anOrientedEdge.IsNull())
4712           continue;
4713         Handle(StepShape_Edge) anEdge = anOrientedEdge->EdgeElement();
4714         if (anEdge.IsNull())
4715           continue;
4716
4717         // Record CAF data
4718         SettleShapeData(anEdge, RootLab, ShapeTool, TP);
4719
4720         // Access vertices
4721         Handle(StepShape_Vertex) aV1 = anEdge->EdgeStart();
4722         Handle(StepShape_Vertex) aV2 = anEdge->EdgeEnd();
4723
4724         // Record CAF data
4725         SettleShapeData(aV1, RootLab, ShapeTool, TP);
4726         SettleShapeData(aV2, RootLab, ShapeTool, TP);
4727       }
4728     }
4729   }
4730 }
4731
4732 //=======================================================================
4733 //function : SetColorMode
4734 //purpose  : 
4735 //=======================================================================
4736
4737 void STEPCAFControl_Reader::SetColorMode(const Standard_Boolean colormode)
4738 {
4739   myColorMode = colormode;
4740 }
4741
4742 //=======================================================================
4743 //function : GetColorMode
4744 //purpose  : 
4745 //=======================================================================
4746
4747 Standard_Boolean STEPCAFControl_Reader::GetColorMode() const
4748 {
4749   return myColorMode;
4750 }
4751
4752 //=======================================================================
4753 //function : SetNameMode
4754 //purpose  : 
4755 //=======================================================================
4756
4757 void STEPCAFControl_Reader::SetNameMode(const Standard_Boolean namemode)
4758 {
4759   myNameMode = namemode;
4760 }
4761
4762 //=======================================================================
4763 //function : GetNameMode
4764 //purpose  : 
4765 //=======================================================================
4766
4767 Standard_Boolean STEPCAFControl_Reader::GetNameMode() const
4768 {
4769   return myNameMode;
4770 }
4771
4772 //=======================================================================
4773 //function : SetLayerMode
4774 //purpose  : 
4775 //=======================================================================
4776
4777 void STEPCAFControl_Reader::SetLayerMode(const Standard_Boolean layermode)
4778 {
4779   myLayerMode = layermode;
4780 }
4781
4782 //=======================================================================
4783 //function : GetLayerMode
4784 //purpose  : 
4785 //=======================================================================
4786
4787 Standard_Boolean STEPCAFControl_Reader::GetLayerMode() const
4788 {
4789   return myLayerMode;
4790 }
4791
4792 //=======================================================================
4793 //function : SetPropsMode
4794 //purpose  : 
4795 //=======================================================================
4796
4797 void STEPCAFControl_Reader::SetPropsMode(const Standard_Boolean propsmode)
4798 {
4799   myPropsMode = propsmode;
4800 }
4801
4802 //=======================================================================
4803 //function : GetPropsMode
4804 //purpose  : 
4805 //=======================================================================
4806
4807 Standard_Boolean STEPCAFControl_Reader::GetPropsMode() const
4808 {
4809   return myPropsMode;
4810 }
4811
4812 //=======================================================================
4813 //function : SetSHUOMode
4814 //purpose  : 
4815 //=======================================================================
4816
4817 void STEPCAFControl_Reader::SetSHUOMode(const Standard_Boolean mode)
4818 {
4819   mySHUOMode = mode;
4820 }
4821
4822 //=======================================================================
4823 //function : GetSHUOMode
4824 //purpose  : 
4825 //=======================================================================
4826
4827 Standard_Boolean STEPCAFControl_Reader::GetSHUOMode() const
4828 {
4829   return mySHUOMode;
4830 }
4831
4832 //=======================================================================
4833 //function : SetGDTMode
4834 //purpose  : 
4835 //=======================================================================
4836
4837 void STEPCAFControl_Reader::SetGDTMode(const Standard_Boolean gdtmode)
4838 {
4839   myGDTMode = gdtmode;
4840 }
4841
4842 //=======================================================================
4843 //function : GetGDTMode
4844 //purpose  : 
4845 //=======================================================================
4846
4847 Standard_Boolean STEPCAFControl_Reader::GetGDTMode() const
4848 {
4849   return myGDTMode;
4850 }
4851
4852
4853 //=======================================================================
4854 //function : SetMatMode
4855 //purpose  : 
4856 //=======================================================================
4857
4858 void STEPCAFControl_Reader::SetMatMode(const Standard_Boolean matmode)
4859 {
4860   myMatMode = matmode;
4861 }
4862
4863 //=======================================================================
4864 //function : GetMatMode
4865 //purpose  : 
4866 //=======================================================================
4867
4868 Standard_Boolean STEPCAFControl_Reader::GetMatMode() const
4869 {
4870   return myMatMode;
4871 }
4872
4873 //=======================================================================
4874 //function : SetViewMode
4875 //purpose  : 
4876 //=======================================================================
4877
4878 void STEPCAFControl_Reader::SetViewMode(const Standard_Boolean viewmode)
4879 {
4880   myViewMode = viewmode;
4881 }
4882
4883 //=======================================================================
4884 //function : GetViewMode
4885 //purpose  : 
4886 //=======================================================================
4887
4888 Standard_Boolean STEPCAFControl_Reader::GetViewMode() const
4889 {
4890   return myViewMode;
4891 }