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