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