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