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