7d329c9ef033f883d8056e194620a7698d8f405a
[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     NCollection_Vector<Handle(MMgt_TShared)> anItems;
918     if (!style->Item().IsNull()) {
919       anItems.Append(style->Item());
920     }
921     else if (!style->ItemAP242().Representation().IsNull()){
922       //special case for AP242: item can be Reprsentation
923       Handle(StepRepr_Representation) aRepr = style->ItemAP242().Representation();
924       for (Standard_Integer i = 1; i <= aRepr->Items()->Length(); i++)
925         anItems.Append(aRepr->Items()->Value(i));
926     }
927     for (Standard_Integer itemIt = 0; itemIt < anItems.Length(); itemIt++) {
928       TopoDS_Shape S = STEPConstruct::FindShape ( Styles.TransientProcess(),
929         Handle(StepRepr_RepresentationItem)::DownCast(anItems.Value(itemIt)) );
930       Standard_Boolean isSkipSHUOstyle = Standard_False;
931       // take shape with real location.
932       while ( IsComponent ) {
933         // take SR of NAUO
934         Handle(StepShape_ShapeRepresentation) aSR;
935         findStyledSR( style, aSR );
936         // search for SR along model
937         if (aSR.IsNull())
938           break;
939         Handle(XSControl_TransferReader) TR = WS->TransferReader();
940         Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
941         Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
942         Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
943         for (subs.Start(); subs.More(); subs.Next()) {
944           aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
945           if ( aSDR.IsNull() )
946             continue;
947           StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
948           Handle(StepRepr_ProductDefinitionShape) PDS = 
949             Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
950           if ( PDS.IsNull() )
951             continue;
952           StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
953           
954           Handle(StepRepr_AssemblyComponentUsage) ACU = 
955             Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
956           // PTV 10.02.2003 skip styled item that refer to SHUO
957           if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
958             isSkipSHUOstyle = Standard_True;
959             break;
960           }
961           Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
962             Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
963           if ( NAUO.IsNull() )
964             continue;
965           
966           TopoDS_Shape aSh;
967           // PTV 10.02.2003 to find component of assembly CORRECTLY
968           STEPConstruct_Tool Tool( WS );
969           TDF_Label aShLab = FindInstance ( NAUO, CTool->ShapeTool(), Tool, PDFileMap, ShapeLabelMap );
970           aSh = CTool->ShapeTool()->GetShape(aShLab);
971           if (!aSh.IsNull()) {
972             S = aSh;
973             break;
974           }
975         }
976         break;
977       }
978       if (isSkipSHUOstyle)
979         continue; // skip styled item which refer to SHUO
980       
981       if ( S.IsNull() )
982         continue;
983       
984       if ( ! SurfCol.IsNull() ) {
985         Quantity_Color col;
986         Styles.DecodeColor ( SurfCol, col );
987         if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorSurf ))
988           SetColorToSubshape( CTool, S, col, XCAFDoc_ColorSurf );
989       }
990       if ( ! BoundCol.IsNull() ) {
991         Quantity_Color col;
992         Styles.DecodeColor ( BoundCol, col );
993         if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
994           SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
995       }
996       if ( ! CurveCol.IsNull() ) {
997         Quantity_Color col;
998         Styles.DecodeColor ( CurveCol, col );
999         if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
1000           SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
1001       }
1002       if ( !IsVisible ) {
1003         // sets the invisibility for shape.
1004         TDF_Label aInvL;
1005         if ( CTool->ShapeTool()->Search( S, aInvL ) )
1006           CTool->SetVisibility( aInvL, Standard_False );
1007       }
1008     }
1009   }
1010   CTool->ReverseChainsOfTreeNodes();
1011   return Standard_True;
1012 }
1013
1014 //=======================================================================
1015 //function : GetLabelFromPD
1016 //purpose  : 
1017 //=======================================================================
1018
1019 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1020                                  const Handle(XCAFDoc_ShapeTool) &STool,
1021                                  const Handle(Transfer_TransientProcess) &TP,
1022                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1023                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1024 {
1025   TDF_Label L;
1026   if ( PDFileMap.IsBound ( PD ) ) {
1027     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1028     if ( ! EF.IsNull() ) {
1029       L = EF->GetLabel();
1030       if ( ! L.IsNull() ) return L;
1031     }
1032   }
1033
1034   TopoDS_Shape S;
1035   Handle(Transfer_Binder) binder = TP->Find(PD);
1036   if ( binder.IsNull() || ! binder->HasResult() ) return L;
1037   S = TransferBRep::ShapeResult ( TP, binder );
1038   if ( S.IsNull() ) return L;
1039
1040   if ( S.IsNull() ) return L;
1041   if ( ShapeLabelMap.IsBound ( S ) )
1042     L = ShapeLabelMap.Find ( S );
1043   if ( L.IsNull() )
1044     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1045   return L;
1046 }
1047
1048 //=======================================================================
1049 //function : FindInstance
1050 //purpose  : 
1051 //=======================================================================
1052
1053 TDF_Label STEPCAFControl_Reader::FindInstance (const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
1054                                                const Handle(XCAFDoc_ShapeTool) &STool,
1055                                                const STEPConstruct_Tool &Tool,
1056                                                const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1057                                                const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1058 {
1059   TDF_Label L;
1060   
1061   // get shape resulting from CDSR (in fact, only location is interesting)
1062   Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
1063   Handle(Transfer_Binder) binder = TP->Find(NAUO);
1064   if ( binder.IsNull() || ! binder->HasResult() ) {
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   TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1072   if ( S.IsNull() ) {
1073 #ifdef OCCT_DEBUG
1074     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1075 #endif
1076     return L;
1077   }
1078
1079   // find component`s original label
1080   Handle(StepBasic_ProductDefinition) PD = NAUO->RelatedProductDefinition();
1081   if ( PD.IsNull() ) return L;
1082   TDF_Label Lref = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1083   if ( Lref.IsNull() ) return L;
1084   
1085   // find main shape (assembly) label
1086   PD.Nullify();
1087   PD = NAUO->RelatingProductDefinition();
1088   if ( PD.IsNull() ) return L;
1089   TDF_Label L0 = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1090   if ( L0.IsNull() ) return L;
1091   
1092   // if CDSR and NAUO are reversed, swap labels
1093   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1094   Interface_EntityIterator subs1 = Tool.Graph().Sharings(NAUO);
1095   for (subs1.Start(); subs1.More(); subs1.Next()) {
1096     Handle(StepRepr_ProductDefinitionShape) PDS = 
1097       Handle(StepRepr_ProductDefinitionShape)::DownCast(subs1.Value());
1098     if(PDS.IsNull()) continue;
1099     Interface_EntityIterator subs2 = Tool.Graph().Sharings(PDS);
1100     for (subs2.Start(); subs2.More(); subs2.Next()) {
1101       Handle(StepShape_ContextDependentShapeRepresentation) CDSRtmp = 
1102         Handle(StepShape_ContextDependentShapeRepresentation)::DownCast(subs2.Value());
1103       if (CDSRtmp.IsNull()) continue;
1104       CDSR = CDSRtmp;
1105     }
1106   }
1107   if (CDSR.IsNull()) return L;
1108 //  if ( STEPConstruct_Assembly::CheckSRRReversesNAUO ( Tool.Model(), CDSR ) ) {
1109 //    TDF_Label Lsw = L0; L0 = Lref; Lref = Lsw;
1110 //  }
1111   
1112   // iterate on components to find proper one
1113   TDF_LabelSequence seq;
1114   XCAFDoc_ShapeTool::GetComponents ( L0, seq );
1115   for ( Standard_Integer k=1; L.IsNull() && k <= seq.Length(); k++ ) {
1116     TDF_Label Lcomp = seq(k), Lref2;
1117     if ( XCAFDoc_ShapeTool::GetReferredShape ( Lcomp, Lref2 ) && 
1118         Lref2 == Lref &&
1119         S.Location() == XCAFDoc_ShapeTool::GetLocation ( Lcomp ) ) 
1120       L = Lcomp;
1121   }
1122   
1123   return L;
1124 }
1125
1126 //=======================================================================
1127 //function : ReadNames
1128 //purpose  : 
1129 //=======================================================================
1130
1131 Standard_Boolean STEPCAFControl_Reader::ReadNames (const Handle(XSControl_WorkSession) &WS,
1132                                                    Handle(TDocStd_Document)& Doc,
1133                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1134                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1135 {
1136   // get starting data
1137   Handle(Interface_InterfaceModel) Model = WS->Model();
1138   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1139   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1140   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1141   if ( STool.IsNull() ) return Standard_False;
1142   STEPConstruct_Tool Tool ( WS );
1143
1144   // iterate on model to find all SDRs and CDSRs
1145   Standard_Integer nb = Model->NbEntities();
1146   Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
1147   Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
1148   Handle(TCollection_HAsciiString) name;
1149   TDF_Label L;
1150   for (Standard_Integer i = 1; i <= nb; i++) {
1151     Handle(Standard_Transient) enti = Model->Value(i);
1152
1153     // get description of NAUO
1154     if ( enti->DynamicType() == tNAUO ) {
1155       L.Nullify();
1156       Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
1157         Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
1158       if(NAUO.IsNull()) continue;
1159       Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
1160       for (subs.Start(); subs.More(); subs.Next()) {
1161         Handle(StepRepr_ProductDefinitionShape) PDS = 
1162           Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1163         if(PDS.IsNull()) continue;
1164         Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
1165         if ( PDR.IsNull() ) continue;
1166         if ( PDR->HasDescription() && 
1167             PDR->Description()->Length() >0 ) name = PDR->Description();
1168         else if ( !PDR->Name().IsNull() && PDR->Name()->Length() >0 ) name = PDR->Name();
1169         else if ( !PDR->Id().IsNull()) name = PDR->Id();
1170         else name = new TCollection_HAsciiString;
1171       }
1172       // find proper label
1173       L = FindInstance ( NAUO, STool, Tool, PDFileMap, ShapeLabelMap );
1174       if ( L.IsNull() ) continue;
1175       TCollection_ExtendedString str ( name->String() );
1176       TDataStd_Name::Set ( L, str );
1177     }
1178
1179     // for PD get name of associated product
1180     if ( enti->DynamicType() == tPD ) {
1181       L.Nullify();
1182       Handle(StepBasic_ProductDefinition) PD = 
1183         Handle(StepBasic_ProductDefinition)::DownCast(enti);
1184       if(PD.IsNull()) continue;
1185       Handle(StepBasic_Product) Prod = (!PD->Formation().IsNull() ? PD->Formation()->OfProduct() : NULL);
1186       if (Prod.IsNull())
1187         name = new TCollection_HAsciiString;
1188       else if (!Prod->Name().IsNull() && Prod->Name()->UsefullLength() > 0) 
1189         name = Prod->Name();
1190       else if (!Prod->Id().IsNull()) 
1191         name = Prod->Id();
1192       else 
1193         name = new TCollection_HAsciiString;
1194       L = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1195       if ( L.IsNull() ) continue;
1196       TCollection_ExtendedString str ( name->String() );
1197       TDataStd_Name::Set ( L, str );
1198     }
1199     // set a name to the document
1200     //TCollection_ExtendedString str ( name->String() );
1201     //TDataStd_Name::Set ( L, str );
1202   }
1203
1204   return Standard_True;
1205 }
1206
1207 //=======================================================================
1208 //function : GetLabelFromPD
1209 //purpose  : 
1210 //=======================================================================
1211
1212 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1213                                  const Handle(XCAFDoc_ShapeTool) &STool,
1214                                  const STEPConstruct_ValidationProps &Props,
1215                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1216                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1217 {
1218   TDF_Label L;
1219   if ( PDFileMap.IsBound ( PD ) ) {
1220     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1221     if ( ! EF.IsNull() ) {
1222       L = EF->GetLabel();
1223       if ( ! L.IsNull() ) return L;
1224     }
1225   }
1226   TopoDS_Shape S = Props.GetPropShape ( PD );
1227   if ( S.IsNull() ) return L;
1228   if ( ShapeLabelMap.IsBound ( S ) )
1229     L = ShapeLabelMap.Find ( S );
1230   if ( L.IsNull() )
1231     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1232   return L;
1233 }
1234
1235 //=======================================================================
1236 //function : ReadValProps
1237 //purpose  : 
1238 //=======================================================================
1239
1240 Standard_Boolean STEPCAFControl_Reader::ReadValProps (const Handle(XSControl_WorkSession) &WS,
1241                                                       Handle(TDocStd_Document)& Doc,
1242                                                       const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1243                                                       const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1244 {
1245   // get starting data
1246   Handle(Interface_InterfaceModel) Model = WS->Model();
1247   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1248   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1249   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1250   if ( STool.IsNull() ) return Standard_False;
1251
1252   // load props from the STEP model
1253   TColStd_SequenceOfTransient props;
1254   STEPConstruct_ValidationProps Props ( WS );
1255   if ( ! Props.LoadProps ( props ) ) {
1256 #ifdef OCCT_DEBUG
1257     cout << "Warning: no validation props found in the model" << endl;
1258 #endif
1259     return Standard_False;
1260   }
1261
1262   // interpret props one by one
1263   for (Standard_Integer i = 1; i <= props.Length(); i ++) {
1264     Handle(StepRepr_PropertyDefinitionRepresentation) PDR = 
1265       Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast ( props.Value(i) );
1266     if ( PDR.IsNull() ) continue;
1267
1268     TDF_Label L;
1269
1270     Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
1271     Interface_EntityIterator subs = Props.Graph().Shareds(PD);
1272     for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
1273       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)) ) {
1274         Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1275         if(PDS.IsNull()) continue;
1276         // find corresponding NAUO
1277         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
1278         Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
1279         for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
1280           if ( subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)) ) 
1281             NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
1282         }
1283         if ( !NAUO.IsNull() ) {
1284           L = FindInstance ( NAUO, STool, WS, PDFileMap, ShapeLabelMap );
1285           if ( L.IsNull() ) continue;
1286         }
1287         else {
1288           // find corresponding ProductDefinition:
1289           Handle(StepBasic_ProductDefinition) ProdDef;
1290           Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
1291           for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
1292             if ( subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)) ) 
1293               ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
1294           }
1295           if ( ProdDef.IsNull() ) continue;
1296           L = GetLabelFromPD ( ProdDef, STool, Props, PDFileMap, ShapeLabelMap );
1297         }
1298       }
1299
1300       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)) ) {
1301         Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
1302         if(SA.IsNull()) continue;
1303         // find ShapeRepresentation
1304         Handle(StepShape_ShapeRepresentation) SR;
1305         Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
1306         for(subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
1307           Handle(StepRepr_PropertyDefinition) PropD1 = 
1308             Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
1309           if(PropD1.IsNull()) continue;
1310           Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
1311           for(subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
1312             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1313               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
1314             if(SDR.IsNull()) continue;
1315             SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1316           }
1317         }
1318         if(SR.IsNull()) continue;
1319         Handle(Transfer_Binder) binder;
1320         for(Standard_Integer ir=1; ir<=SR->NbItems() && binder.IsNull(); ir++) {
1321           if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
1322             Handle(StepShape_SolidModel) SM = 
1323               Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
1324             binder = TP->Find(SM);
1325           }
1326           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1327             Handle(StepShape_ShellBasedSurfaceModel) SBSM =
1328               Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
1329             binder = TP->Find(SBSM);
1330           }
1331           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1332             Handle(StepShape_GeometricSet) GS =
1333               Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
1334             binder = TP->Find(GS);
1335           }
1336         }
1337         if ( binder.IsNull() || ! binder->HasResult() ) continue;
1338         TopoDS_Shape S;
1339         S = TransferBRep::ShapeResult ( TP, binder );
1340         if(S.IsNull()) continue;
1341         if ( ShapeLabelMap.IsBound ( S ) )
1342           L = ShapeLabelMap.Find ( S );
1343         if ( L.IsNull() )
1344           STool->Search ( S, L, Standard_True, Standard_True, Standard_True );
1345       }
1346     }
1347
1348     if(L.IsNull()) continue;
1349       
1350     // decode validation properties
1351     Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
1352     for ( Standard_Integer j=1; j <= rep->NbItems(); j++ ) {
1353       Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
1354       Standard_Boolean isArea;
1355       Standard_Real val;
1356       gp_Pnt pos;
1357       if ( Props.GetPropReal ( ent, val, isArea ) ) {
1358         if ( isArea ) XCAFDoc_Area::Set ( L, val );
1359         else XCAFDoc_Volume::Set ( L, val );
1360       }
1361       else if ( Props.GetPropPnt ( ent, rep->ContextOfItems(), pos ) ) {
1362         XCAFDoc_Centroid::Set ( L, pos );
1363       }
1364     }
1365   }
1366   return Standard_True;
1367 }
1368
1369 //=======================================================================
1370 //function : ReadLayers
1371 //purpose  : 
1372 //=======================================================================
1373
1374 Standard_Boolean STEPCAFControl_Reader::ReadLayers (const Handle(XSControl_WorkSession) &WS,
1375                                                     Handle(TDocStd_Document)& Doc) const
1376 {
1377   Handle(Interface_InterfaceModel) Model = WS->Model();
1378   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1379   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1380   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1381   if ( STool.IsNull() ) return Standard_False;
1382   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( Doc->Main() );
1383   if ( LTool.IsNull() ) return Standard_False;
1384   
1385   Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
1386   Standard_Integer nb = Model->NbEntities();
1387   Handle(TCollection_HAsciiString) name;
1388   
1389   for (Standard_Integer i = 1; i <= nb; i ++) {
1390     Handle(Standard_Transient) enti = Model->Value(i);
1391     if ( ! enti->IsKind ( tSVPLA ) ) continue;
1392     Handle(StepVisual_PresentationLayerAssignment) SVPLA = 
1393       Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
1394     
1395     Handle(TCollection_HAsciiString) descr = SVPLA->Description();
1396     Handle(TCollection_HAsciiString) hName = SVPLA->Name();
1397     TCollection_ExtendedString aLayerName ( hName->String() );
1398      
1399     // find a target shape and its label in the document
1400     for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++ ) {
1401       StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
1402       Handle(Transfer_Binder) binder = TP->Find( LI.Value() );
1403       if ( binder.IsNull() || ! binder->HasResult() ) continue;
1404       
1405       TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1406       if ( S.IsNull() ) continue;
1407         
1408       TDF_Label shL;
1409       if ( ! STool->Search ( S, shL, Standard_True, Standard_True, Standard_True ) ) continue;
1410       LTool->SetLayer ( shL, aLayerName );
1411     }
1412     
1413     // check invisibility
1414     Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
1415     for (subs.Start(); subs.More(); subs.Next()) {
1416       if ( ! subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility)) ) continue;
1417 #ifdef OCCT_DEBUG
1418       cout<< "\tLayer \"" << aLayerName << "\" is invisible"<<endl;
1419 #endif
1420       //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
1421       TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
1422       Handle(TDataStd_UAttribute) aUAttr;
1423       aUAttr->Set( InvLayerLab, XCAFDoc::InvisibleGUID() );
1424     }
1425   }
1426   return Standard_True;
1427 }
1428
1429 //=======================================================================
1430 //function : ReadSHUOs
1431 //purpose  : 
1432 //=======================================================================
1433
1434 static Standard_Boolean findNextSHUOlevel (const Handle(XSControl_WorkSession) &WS,
1435                                            const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1436                                            const Handle(XCAFDoc_ShapeTool)& STool,
1437                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1438                                            const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1439                                            TDF_LabelSequence& aLabels)
1440 {
1441   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1442   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1443   for (subs.Start(); subs.More(); subs.Next()) {
1444     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1445       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1446       break;
1447     }
1448   }
1449   if (subSHUO.IsNull())
1450     return Standard_False;
1451   
1452   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = subSHUO->NextUsage();
1453   if (NUNAUO.IsNull())
1454     return Standard_False;
1455 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1456 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1457 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1458 //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1459 //   if ( binder.IsNull() || ! binder->HasResult() )
1460 //     return Standard_False;
1461 //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1462   // get label of NAUO next level
1463   TDF_Label NULab;
1464   STEPConstruct_Tool Tool( WS );
1465   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1466 //   STool->Search(NUSh, NUlab);
1467   if (NULab.IsNull())
1468     return Standard_False;
1469   aLabels.Append( NULab );
1470   // and check by recurse.
1471   findNextSHUOlevel( WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels );
1472   return Standard_True;
1473 }
1474
1475
1476 //=======================================================================
1477 //function : setSHUOintoDoc
1478 //purpose  : auxilary
1479 //=======================================================================
1480 static TDF_Label setSHUOintoDoc (const Handle(XSControl_WorkSession) &WS,
1481                                  const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1482                                  const Handle(XCAFDoc_ShapeTool)& STool,
1483                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1484                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1485 {
1486   TDF_Label aMainLabel;
1487   // get upper usage NAUO from SHUO.
1488   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1489     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1490   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = SHUO->NextUsage();
1491   if ( UUNAUO.IsNull() || NUNAUO.IsNull() ) {
1492 #ifdef OCCT_DEBUG
1493     cout << "Warning: " << __FILE__ <<": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
1494 #endif
1495     return aMainLabel;
1496   }
1497 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1498 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1499 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1500 //   TopoDS_Shape UUSh, NUSh;
1501 //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1502 //   if ( binder.IsNull() || ! binder->HasResult() )
1503 //     return aMainLabel;
1504 //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1505 //   binder = TP->Find(NUNAUO);
1506 //   if ( binder.IsNull() || ! binder->HasResult() )
1507 //     return aMainLabel;
1508 //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1509
1510   // get first labels for first SHUO attribute
1511   TDF_Label UULab, NULab;
1512   STEPConstruct_Tool Tool( WS );
1513   UULab = STEPCAFControl_Reader::FindInstance ( UUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1514   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1515   
1516 //   STool->Search(UUSh, UULab);
1517 //   STool->Search(NUSh, NULab);
1518   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1519   //create sequence fo labels to set SHUO structure into the document
1520   TDF_LabelSequence ShuoLabels;
1521   ShuoLabels.Append( UULab );
1522   ShuoLabels.Append( NULab );
1523   // add all other labels of sub SHUO entities
1524   findNextSHUOlevel( WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels );
1525   // last accord for SHUO
1526   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1527   if ( STool->SetSHUO( ShuoLabels, anSHUOAttr ) )
1528     aMainLabel = anSHUOAttr->Label();
1529   
1530   return aMainLabel;
1531 }
1532
1533
1534 //=======================================================================
1535 //function : ReadSHUOs
1536 //purpose  : 
1537 //=======================================================================
1538
1539 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs (const Handle(XSControl_WorkSession) &WS,
1540                                                    Handle(TDocStd_Document)& Doc,
1541                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1542                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1543 {
1544   // the big part code duplication from ReadColors.
1545   // It is possible to share this code functionality, just to decide how ???
1546   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
1547   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1548   
1549   STEPConstruct_Styles Styles ( WS );
1550   if ( ! Styles.LoadStyles() ) {
1551 #ifdef OCCT_DEBUG
1552     cout << "Warning: no styles are found in the model" << endl;
1553 #endif
1554     return Standard_False;
1555   }
1556   // searching for invisible items in the model
1557   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1558   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
1559   // parse and search for color attributes
1560   Standard_Integer nb = Styles.NbStyles();
1561   for ( Standard_Integer i=1; i <= nb; i++ ) {
1562     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
1563     if ( style.IsNull() ) continue;
1564     
1565     Standard_Boolean IsVisible = Standard_True;
1566     // check the visibility of styled item.
1567     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
1568       if ( style != aHSeqOfInvisStyle->Value( si ) )
1569         continue;
1570       // found that current style is invisible.
1571 #ifdef OCCT_DEBUG
1572       cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
1573 #endif
1574       IsVisible = Standard_False;
1575       break;
1576     }
1577
1578     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
1579     // check if it is component style
1580     Standard_Boolean IsComponent = Standard_False;
1581     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
1582       continue;
1583     if (!IsComponent)
1584       continue;
1585     Handle(StepShape_ShapeRepresentation) aSR;
1586     findStyledSR( style, aSR );
1587     // search for SR along model
1588     if ( aSR.IsNull() )
1589       continue;
1590     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
1591     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1592     for (subs.Start(); subs.More(); subs.Next()) {
1593       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1594       if ( aSDR.IsNull() )
1595         continue;
1596       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1597       Handle(StepRepr_ProductDefinitionShape) PDS = 
1598         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1599       if ( PDS.IsNull() )
1600         continue;
1601       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1602       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1603         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1604       if ( SHUO.IsNull() )
1605         continue;
1606       
1607       // set the SHUO structure to the document
1608       TDF_Label aLabelForStyle = setSHUOintoDoc( WS, SHUO, STool, PDFileMap, ShapeLabelMap );
1609       if ( aLabelForStyle.IsNull() ) {
1610 #ifdef OCCT_DEBUG
1611         cout << "Warning: " << __FILE__ <<": coudnot create SHUO structure in the document" << endl;
1612 #endif
1613         continue;
1614       }
1615       // now set the style to the SHUO main label.
1616       if ( ! SurfCol.IsNull() ) {
1617         Quantity_Color col;
1618         Styles.DecodeColor ( SurfCol, col );
1619         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorSurf );
1620       }
1621       if ( ! BoundCol.IsNull() ) {
1622         Quantity_Color col;
1623         Styles.DecodeColor ( BoundCol, col );
1624         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1625       }
1626       if ( ! CurveCol.IsNull() ) {
1627         Quantity_Color col;
1628         Styles.DecodeColor ( CurveCol, col );
1629         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1630       }
1631       if ( !IsVisible )
1632         // sets the invisibility for shape.
1633         CTool->SetVisibility( aLabelForStyle, Standard_False );
1634       
1635     } // end search SHUO by SDR
1636   } // end iterates on styles
1637       
1638   return Standard_True;
1639 }
1640
1641
1642 //=======================================================================
1643 //function : GetLengthConversionFactor
1644 //purpose  : 
1645 //=======================================================================
1646 static Standard_Boolean GetLengthConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1647                                                   Standard_Real& afact)
1648 {
1649   afact=1.;
1650   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit)) ) return Standard_False;
1651   Handle(StepBasic_ConversionBasedUnitAndLengthUnit) CBULU =
1652     Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(NU);
1653   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1654   afact = MWUCBU->ValueComponent();
1655   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1656   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1657     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1658     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1659       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1660       if(SU->Name()==StepBasic_sunMetre) {
1661         if(SU->HasPrefix()) 
1662           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1663         // convert m to mm
1664         afact *= 1000.;
1665       }
1666     }
1667   }
1668   return Standard_True;
1669 }
1670
1671
1672 //=======================================================================
1673 //function : GetAngleConversionFactor
1674 //purpose  : 
1675 //=======================================================================
1676 static Standard_Boolean GetAngleConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1677                                                   Standard_Real& afact)
1678 {
1679   afact=1.;
1680   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)) ) return Standard_False;
1681   Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit) CBULU =
1682     Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)::DownCast(NU);
1683   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1684   afact = MWUCBU->ValueComponent();
1685   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1686   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1687     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1688     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1689       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1690       if(SU->Name()==StepBasic_sunRadian) {
1691         if(SU->HasPrefix()) 
1692           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1693         // convert radian to deg
1694         afact *= 180/M_PI;
1695       }
1696     }
1697   }
1698   return Standard_True;
1699 }
1700
1701 //=======================================================================
1702 //function : GetMassConversionFactor
1703 //purpose  : 
1704 //=======================================================================
1705 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1706                                                 Standard_Real& afact)
1707 {
1708   afact=1.;
1709   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit)) ) return Standard_False;
1710   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1711     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1712   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1713   afact = MWUCBU->ValueComponent();
1714   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1715   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1716     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1717     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1718       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1719       if(SU->Name()==StepBasic_sunGram) {
1720         if(SU->HasPrefix())
1721           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1722       }
1723     }
1724   }
1725   return Standard_True;
1726 }
1727
1728 //=======================================================================
1729 //function : readAnnotation
1730 //purpose  : return annotation plane and position for given GDT
1731 // (Dimension, Geometric_Tolerance, Datum_Feature or Placed_Datum_Target_Feature)
1732 //=======================================================================
1733 void readAnnotation(const Handle(XSControl_TransferReader)& theTR, 
1734   const Handle(Standard_Transient) theGDT,
1735   const Handle(Standard_Transient)& theDimObject)
1736 {
1737   Handle(TCollection_HAsciiString) aPresentName;
1738   TopoDS_Compound aResAnnotation;
1739   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1740   const Interface_Graph& aGraph = aTP->Graph();
1741   // find the proper DraughtingModelItemAssociation
1742   Interface_EntityIterator subs = aGraph.Sharings(theGDT);
1743   Handle(StepAP242_DraughtingModelItemAssociation) aDMIA;
1744   for (subs.Start(); subs.More() && aDMIA.IsNull(); subs.Next()) {
1745     if (!subs.Value()->IsKind(STANDARD_TYPE(StepAP242_DraughtingModelItemAssociation)))
1746       continue;
1747     aDMIA = Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(subs.Value());
1748     Handle(TCollection_HAsciiString) aName = aDMIA->Name();
1749     aName->LowerCase();
1750     if (!aName->Search(new TCollection_HAsciiString("pmi representation to presentation link"))) {
1751       aDMIA = NULL;
1752     }
1753   }
1754   if (aDMIA.IsNull() || aDMIA->NbIdentifiedItem() == 0)
1755     return;
1756
1757   // retrieve AnnotationPlane
1758   Standard_Boolean isHasPlane = Standard_False;
1759   gp_Ax2 aPlaneAxes;
1760   Handle(StepRepr_RepresentationItem) aDMIAE = aDMIA->IdentifiedItemValue(1);
1761   if (aDMIAE.IsNull())
1762     return;
1763   subs = aGraph.Sharings(aDMIAE);
1764   Handle(StepVisual_AnnotationPlane) anAnPlane;
1765   for (subs.Start(); subs.More() && anAnPlane.IsNull(); subs.Next()) {
1766     anAnPlane = Handle(StepVisual_AnnotationPlane)::DownCast(subs.Value());
1767   }
1768   if (!anAnPlane.IsNull()) {
1769     Handle(StepRepr_RepresentationItem) aPlaneItem = anAnPlane->Item();
1770     Handle(StepGeom_Axis2Placement3d) aA2P3D;
1771     //retrieve axes from AnnotationPlane
1772     if (aPlaneItem->IsKind(STANDARD_TYPE(StepGeom_Plane))) {
1773       Handle(StepGeom_Plane) aPlane = Handle(StepGeom_Plane)::DownCast(aPlaneItem);
1774       aA2P3D = aPlane->Position();
1775     }
1776     else if (aPlaneItem->IsKind(STANDARD_TYPE(StepVisual_PlanarBox))) {
1777       Handle(StepVisual_PlanarBox) aBox = Handle(StepVisual_PlanarBox)::DownCast(aPlaneItem);
1778       aA2P3D = aBox->Placement().Axis2Placement3d();
1779     }
1780     // build gp_Ax2 from axes
1781     if (!aA2P3D.IsNull())
1782     {
1783       Handle(StepGeom_Direction) anAxis = aA2P3D->Axis(), 
1784         aRefDir = aA2P3D->RefDirection();
1785       if (!anAxis.IsNull() && !aRefDir.IsNull()) {
1786         Handle(TColStd_HArray1OfReal) aCoords;
1787         aCoords = anAxis->DirectionRatios();
1788         gp_Dir aXDir(aCoords->Value(1), aCoords->Value(2), aCoords->Value(3));
1789         aCoords = aRefDir->DirectionRatios();
1790         gp_Dir aYDir(aCoords->Value(1), aCoords->Value(2), aCoords->Value(3));
1791         aPlaneAxes.SetDirection(aXDir.Crossed(aYDir));
1792         aPlaneAxes.SetYDirection(aYDir);
1793         //set location of the annotation plane
1794         Handle(TColStd_HArray1OfReal) aLocCoords;
1795         Handle(StepGeom_CartesianPoint) aLoc = aA2P3D->Location();
1796         gp_Pnt aLocPos( aLoc->CoordinatesValue (1), aLoc->CoordinatesValue (2), aLoc->CoordinatesValue (3));
1797         aPlaneAxes.SetLocation(aLocPos);
1798         isHasPlane = Standard_True;
1799       }
1800     }
1801   }
1802
1803   // set plane axes to XCAF
1804   if (isHasPlane) {
1805     if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1806       Handle(XCAFDimTolObjects_DimensionObject) anObj = 
1807         Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1808
1809       Handle(TColgp_HArray1OfPnt) aPnts = new TColgp_HArray1OfPnt(1, 1);
1810       anObj->SetPlane(aPlaneAxes);
1811     
1812
1813     }
1814     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1815       Handle(XCAFDimTolObjects_DatumObject) anObj =
1816         Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1817       anObj->SetPlane(aPlaneAxes);
1818       
1819     }
1820     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1821       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1822         Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1823       anObj->SetPlane(aPlaneAxes);
1824      
1825     }
1826   }
1827
1828
1829   // Retrieve presentation
1830   Handle(StepVisual_AnnotationCurveOccurrence) anACO;
1831   NCollection_Vector<Handle(StepVisual_TessellatedAnnotationOccurrence)> aTesselations;
1832   NCollection_Vector<Handle(StepVisual_StyledItem)> anAnnotations;
1833   if (aDMIAE->IsKind(STANDARD_TYPE(StepVisual_AnnotationCurveOccurrence))) 
1834   {
1835     anACO = Handle(StepVisual_AnnotationCurveOccurrence)::DownCast(aDMIAE);
1836     if( !anACO.IsNull())
1837       anAnnotations.Append(anACO);
1838   }
1839
1840   else if (aDMIAE->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout))) 
1841   {
1842     Handle(StepVisual_DraughtingCallout) aDCallout =
1843       Handle(StepVisual_DraughtingCallout)::DownCast(aDMIAE);
1844     for (Standard_Integer i = 1; i <= aDCallout->NbContents() && anACO.IsNull(); i++) {
1845       anACO = aDCallout->ContentsValue(i).AnnotationCurveOccurrence();
1846       if(!anACO.IsNull())
1847       {
1848         anAnnotations.Append(anACO);
1849         continue;
1850       }
1851       Handle(StepVisual_TessellatedAnnotationOccurrence) aTesselation = 
1852         aDCallout->ContentsValue(i).TessellatedAnnotationOccurrence();
1853       if( !aTesselation.IsNull())
1854         anAnnotations.Append(aTesselation);
1855     }
1856   }
1857
1858   if (!anAnnotations.Length())
1859     return;
1860
1861
1862   BRep_Builder aB;
1863   aB.MakeCompound(aResAnnotation);
1864
1865   Standard_Integer i =0;
1866   Bnd_Box aBox;
1867   Standard_Integer nbShapes =0;
1868   for( ; i < anAnnotations.Length(); i++)
1869   {
1870     Handle(StepVisual_StyledItem) anItem = anAnnotations(i);
1871   
1872     aPresentName = anItem->Name();
1873
1874     anACO = Handle(StepVisual_AnnotationCurveOccurrence)::DownCast(anItem);
1875     TopoDS_Shape anAnnotationShape;
1876     if(!anACO.IsNull())
1877     {
1878       Handle(StepRepr_RepresentationItem) aCurveItem = anACO->Item();
1879       anAnnotationShape = STEPConstruct::FindShape (aTP,aCurveItem);
1880       if( anAnnotationShape.IsNull())
1881       {
1882         Handle(Transfer_Binder) binder = theTR->Actor()->Transfer(aCurveItem, aTP);
1883         if ( ! binder.IsNull() && binder->HasResult() ) {
1884           anAnnotationShape = TransferBRep::ShapeResult ( aTP, binder );
1885         }
1886       }
1887     }
1888     //case of tesselated entities
1889     else
1890     {
1891       Handle(StepRepr_RepresentationItem) aTessItem = anItem->Item();
1892       if(aTessItem.IsNull())
1893         continue;
1894       Handle(StepVisual_TessellatedGeometricSet) aTessSet = Handle(StepVisual_TessellatedGeometricSet)::DownCast(aTessItem);
1895       if( aTessSet.IsNull())
1896         continue;
1897       NCollection_Handle<StepVisual_Array1OfTessellatedItem> aListItems = aTessSet->Items();
1898       Standard_Integer nb = aListItems.IsNull() ? 0 : aListItems->Length();
1899       Handle(StepVisual_TessellatedCurveSet) aTessCurve;
1900       for (Standard_Integer n = 1; n <= nb && aTessCurve.IsNull(); n++)
1901       {
1902         aTessCurve = Handle(StepVisual_TessellatedCurveSet)::DownCast(aListItems->Value(n));
1903       }
1904       if( aTessCurve.IsNull())
1905         continue;
1906       Handle(StepVisual_CoordinatesList) aCoordList = aTessCurve->CoordList();
1907       if( aCoordList.IsNull())
1908         continue;
1909       Handle(TColgp_HArray1OfXYZ)  aPoints = aCoordList->Points();
1910
1911       if (aPoints.IsNull() || aPoints->Length() == 0)
1912         continue;
1913       NCollection_Handle<StepVisual_VectorOfHSequenceOfInteger> aCurves = aTessCurve->Curves();
1914       Standard_Integer aNbC = (aCurves.IsNull() ? 0 : aCurves->Length());
1915       TopoDS_Compound aComp;
1916       aB.MakeCompound(aComp);
1917       
1918       Standard_Integer k = 0;
1919       for( ; k < aNbC; k++)
1920       {
1921         Handle(TColStd_HSequenceOfInteger) anIndexes = aCurves->Value(k);
1922         TopoDS_Wire aCurW;
1923         aB.MakeWire(aCurW);
1924
1925         for(Standard_Integer n = 1; n < anIndexes->Length(); n++)
1926         {
1927           Standard_Integer ind = anIndexes->Value(n);
1928           Standard_Integer indnext = anIndexes->Value(n + 1);
1929           if( ind > aPoints->Length() || indnext > aPoints->Length())
1930             continue;
1931           gp_Pnt aP1(aPoints->Value(ind));
1932           gp_Pnt aP2(aPoints->Value(indnext));
1933           BRepBuilderAPI_MakeEdge aMaker(aP1, aP2);
1934           if( aMaker.IsDone())
1935           {
1936             TopoDS_Edge aCurE = aMaker.Edge();
1937             aB.Add(aCurW, aCurE);
1938           }
1939         }
1940         aB.Add(aComp, aCurW);
1941       }
1942       anAnnotationShape = aComp;
1943     }
1944     if(!anAnnotationShape.IsNull())
1945     {
1946       nbShapes++;
1947       aB.Add(aResAnnotation, anAnnotationShape);
1948       if( i == anAnnotations.Length() - 1)
1949         BRepBndLib::AddClose(anAnnotationShape, aBox);
1950     }
1951   }
1952   
1953   if(!nbShapes)
1954     return;
1955   gp_Pnt aPtext(0., 0., 0.);
1956   if(!aBox.IsVoid())
1957   {
1958     Standard_Real aXmin, aYmin, aZmin,aXmax, aYmax, aZmax; 
1959     aBox.Get(aXmin, aYmin, aZmin,aXmax, aYmax, aZmax);
1960     aPtext = gp_Pnt((aXmin + aXmax) * 0.5, (aYmin + aYmax) * 0.5, (aZmin + aZmax) * 0.5);
1961   }
1962
1963   // set point to XCAF
1964   if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1965     Handle(XCAFDimTolObjects_DimensionObject) anObj = 
1966       Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1967     anObj->SetPointTextAttach(aPtext);
1968     anObj->SetPresentation(aResAnnotation, aPresentName);
1969   }
1970   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1971     Handle(XCAFDimTolObjects_DatumObject) anObj =
1972       Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1973       anObj->SetPointTextAttach(aPtext);
1974       anObj->SetPresentation(aResAnnotation, aPresentName);
1975   }
1976   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1977     Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1978       Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1979     anObj->SetPointTextAttach(aPtext);
1980     anObj->SetPresentation(aResAnnotation, aPresentName);
1981   }
1982   return;
1983 }
1984
1985 //=======================================================================
1986 //function : ReadDatums
1987 //purpose  : auxilary
1988 //=======================================================================
1989 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
1990                                    const Handle(XCAFDoc_DimTolTool) &DGTTool,
1991                                    const Interface_Graph &graph,
1992                                    const Handle(Transfer_TransientProcess) &TP,
1993                                    const TDF_Label TolerL,
1994                                    const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
1995 {
1996   if(GTWDR.IsNull()) return Standard_False;
1997   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
1998   if(HADR.IsNull()) return Standard_False;
1999   for(Standard_Integer idr=1; idr<=HADR->Length(); idr++) {
2000     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
2001     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
2002     if(aDatum.IsNull()) continue;
2003     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
2004     for(subs4.Start(); subs4.More(); subs4.Next()) {
2005       Handle(StepRepr_ShapeAspectRelationship) SAR = 
2006         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
2007       if(SAR.IsNull()) continue;
2008       Handle(StepDimTol_DatumFeature) DF = 
2009         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
2010       if(DF.IsNull()) continue;
2011       Interface_EntityIterator subs5 = graph.Sharings(DF);
2012       Handle(StepRepr_PropertyDefinition) PropDef;
2013       for(subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
2014         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
2015       }
2016       if(PropDef.IsNull()) continue;
2017       Handle(StepShape_AdvancedFace) AF;
2018       subs5 = graph.Sharings(PropDef);
2019       for(subs5.Start(); subs5.More(); subs5.Next()) {
2020         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2021           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
2022         if(!SDR.IsNull()) {
2023           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2024           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2025             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
2026             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2027           }
2028         }
2029       }
2030       if(AF.IsNull()) return Standard_False;
2031       Standard_Integer index = TP->MapIndex(AF);
2032       TopoDS_Shape aSh;
2033       if(index >0) {
2034         Handle(Transfer_Binder) binder = TP->MapItem(index);
2035         aSh = TransferBRep::ShapeResult(binder);
2036       }
2037       if(aSh.IsNull()) continue; 
2038       TDF_Label shL;
2039       if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2040       DGTTool->SetDatum(shL,TolerL,PropDef->Name(),PropDef->Description(),aDatum->Identification());
2041     }
2042   }
2043   return Standard_True;
2044 }
2045
2046
2047 //=======================================================================
2048 //function : setDatumToXCAF
2049 //purpose  : 
2050 //=======================================================================
2051 static Standard_Boolean setDatumToXCAF(const Handle(StepDimTol_Datum)& theDat,
2052                                         const TDF_Label theGDTL,
2053                                         const Standard_Integer thePositionCounter,
2054                                         const XCAFDimTolObjects_DatumModifiersSequence& aXCAFModifiers,
2055                                         const XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal,
2056                                         const Standard_Real aModifValue,
2057                                         const Handle(TDocStd_Document)& theDoc,
2058                                         const Handle(XSControl_WorkSession)& theWS)
2059 {
2060   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2061   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2062   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2063   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2064   const Interface_Graph& aGraph = aTP->Graph();
2065   Handle(XCAFDoc_Datum) aDat;
2066   TDF_Label aShL;
2067   Standard_Boolean aRefShapeIsFound = Standard_False;
2068   Standard_Boolean aFirstStep = Standard_True;
2069   Interface_EntityIterator anIterD = aGraph.Sharings(theDat);
2070   for(anIterD.Start(); anIterD.More(); anIterD.Next()) {
2071     Handle(StepRepr_ShapeAspectRelationship) aSAR = 
2072       Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterD.Value());
2073     if(aSAR.IsNull()) continue;
2074
2075     Handle(StepRepr_ShapeAspect) aSA = aSAR->RelatingShapeAspect();
2076     if (aSA.IsNull()) continue;
2077     Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
2078     if(aSA->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2079     {
2080       //processing for complex entity
2081       Interface_EntityIterator anIterC = aGraph.Sharings(aSA);
2082       for(anIterC.Start(); anIterC.More(); anIterC.Next()) {
2083         Handle(StepRepr_ShapeAspectRelationship) SAR = 
2084           Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterC.Value());
2085         if(SAR.IsNull()) continue;
2086         Handle(StepRepr_ShapeAspect) aS = SAR->RelatedShapeAspect();
2087         if(aS.IsNull()) continue;
2088         Interface_EntityIterator anIterSA = aGraph.Sharings(aS);
2089         for(anIterSA.Start(); anIterSA.More() && aPGISU.IsNull(); anIterSA.Next()) {
2090           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2091         }
2092         if(!aPGISU.IsNull()){
2093           aSA = aS;
2094           break;
2095         }
2096       }
2097     }
2098     else if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
2099     {
2100       //processing for datum target
2101       Interface_EntityIterator anIterDTF = aGraph.Sharings(aSA);
2102       for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2103         if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_FeatureForDatumTargetRelationship)))
2104         {
2105           Handle(StepRepr_FeatureForDatumTargetRelationship) aFFDTR =
2106             Handle(StepRepr_FeatureForDatumTargetRelationship)::DownCast(anIterDTF.Value());
2107           Handle(StepRepr_ShapeAspect) aTmpSA = aFFDTR->RelatedShapeAspect();
2108           Interface_EntityIterator anIterDSWP = aGraph.Sharings(aTmpSA);
2109           for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
2110             aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2111     }
2112         }
2113       }
2114     }
2115     if (aSA.IsNull()) continue;
2116     Interface_EntityIterator anIterDSWP = aGraph.Sharings(aSA);
2117     for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
2118       aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2119     }
2120     if(aPGISU.IsNull()) continue;
2121     // get representation item
2122     Handle(StepRepr_RepresentationItem) aRI;
2123     for(Standard_Integer i = 1 ; i <= aPGISU->NbIdentifiedItem() && aRI.IsNull(); i++)
2124     {
2125       aRI = aPGISU->IdentifiedItemValue(i);
2126     }
2127     if(aRI.IsNull()) continue;
2128     Standard_Integer index = aTP->MapIndex(aRI);
2129     TopoDS_Shape aSh;
2130     if(index >0) {
2131       Handle(Transfer_Binder) binder = aTP->MapItem(index);
2132       aSh = TransferBRep::ShapeResult(binder);
2133     }
2134     if(aSh.IsNull()) continue; 
2135     if( !aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True) ) continue;
2136     Handle(TDataStd_TreeNode) aNode;
2137     if(aFirstStep && aShL.FindAttribute(XCAFDoc::DatumRefGUID(),aNode) && aNode->HasFirst() &&
2138        aNode->First()->Label().FindAttribute(XCAFDoc_Datum::GetID(),aDat))
2139     {
2140       //if datums already attached, not need add datum target
2141       aRefShapeIsFound = Standard_True;
2142     }
2143     aFirstStep = Standard_False;
2144     Handle(XCAFDimTolObjects_DatumObject) aDatObj;
2145     if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
2146     {
2147       if(!aRefShapeIsFound)
2148       {
2149         //if datum targers not yet added
2150         TDF_Label aDatL = aDGTTool->AddDatum();
2151         aDat = XCAFDoc_Datum::Set(aDatL);
2152         aDGTTool->SetDatum(aShL, aDatL);
2153         aDatObj = aDat->GetObject();
2154         aDatObj->SetName(theDat->Identification());
2155         aDatObj->SetPosition (thePositionCounter);
2156         if(!aXCAFModifiers.IsEmpty())
2157           aDatObj->SetModifiers(aXCAFModifiers);
2158         if (aXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None) 
2159           aDatObj->SetModifierWithValue(aXCAFModifWithVal, aModifValue);
2160         aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2161         Handle(StepDimTol_PlacedDatumTargetFeature) aPDTF = Handle(StepDimTol_PlacedDatumTargetFeature)::DownCast(aSA);
2162         if (aPDTF->TargetId()->IsIntegerValue())
2163           aDatObj->SetDatumTargetNumber(aPDTF->TargetId()->IntegerValue());
2164         else
2165           aDatObj->SetDatumTargetNumber(0);
2166         aDatObj->IsDatumTarget(Standard_True);
2167         XCAFDimTolObjects_DatumTargetType aType;
2168         if(STEPCAFControl_GDTProperty::GetDatumTargetType(aSA->Description(),aType))
2169         {
2170           aDatObj->SetDatumTargetType(aType);
2171           if(aType == XCAFDimTolObjects_DatumTargetType_Area)
2172           {
2173             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
2174             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2175               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2176               {
2177                 Handle(StepAP242_GeometricItemSpecificUsage) aGISU
2178                   = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2179                 Handle(StepRepr_RepresentationItem) anItem;
2180                 if(aPGISU->NbIdentifiedItem() > 0) {
2181                   anItem = aPGISU->IdentifiedItemValue(1);
2182                 }
2183                 if(anItem.IsNull()) continue;
2184                 Standard_Integer anItemIndex = aTP->MapIndex(anItem);
2185                 if(anItemIndex >0) {
2186                   Handle(Transfer_Binder) binder = aTP->MapItem(anItemIndex);
2187                   TopoDS_Shape anItemShape = TransferBRep::ShapeResult(binder);
2188                   aDatObj->SetDatumTarget(anItemShape);
2189                 }
2190               }
2191             }
2192           }
2193           else
2194           {
2195             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
2196             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2197               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_PropertyDefinition)))
2198               {
2199                 Interface_EntityIterator anIterPD = aGraph.Shareds(anIterDTF.Value());
2200                 for(anIterPD.Start(); anIterPD.More(); anIterPD.Next()) {
2201                   if(anIterPD.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2202                   {
2203                     Interface_EntityIterator anIterSDR = aGraph.Sharings(anIterPD.Value());
2204                     for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) {
2205                       if(anIterSDR.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeRepresentationWithParameters)))
2206                       {
2207                         Handle(StepShape_ShapeRepresentationWithParameters) aSRWP
2208                           = Handle(StepShape_ShapeRepresentationWithParameters)::DownCast(anIterSDR.Value());
2209                         for(Standard_Integer r = aSRWP->Items()->Lower(); r <= aSRWP->Items()->Upper(); r++)
2210                         {
2211                           if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2212                           {
2213                             Handle(StepGeom_Axis2Placement3d) anAx
2214                               = Handle(StepGeom_Axis2Placement3d)::DownCast(aSRWP->ItemsValue(r));
2215                             Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2216                             Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2217                             Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2218                             gp_Dir aDir;
2219                             gp_Dir aDirR;
2220                             gp_Pnt aPnt;
2221                             if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2222                               !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2223                               !aLocArr.IsNull() && aLocArr->Length() > 2)
2224                             {
2225                               aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2226                               aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2227                               aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2228                               gp_Ax2 anA(aPnt, aDir, aDirR);
2229                               aDatObj->SetDatumTargetAxis(anA);
2230                             }
2231                           }
2232                           else if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit)))
2233                           {
2234                             Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aM =
2235                               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aSRWP->ItemsValue(r)); 
2236                             Standard_Real aVal = aM->GetMeasureWithUnit()->ValueComponent();
2237                             StepBasic_Unit anUnit = aM->GetMeasureWithUnit()->UnitComponent();
2238                             Standard_Real aFact=1.;
2239                             if(anUnit.IsNull()) continue;
2240                             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2241                             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2242                             if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2243                             if(aM->Name()->String().IsEqual("target length") ||
2244                               aM->Name()->String().IsEqual("target diameter"))
2245                               aDatObj->SetDatumTargetLength(aVal);
2246                             else
2247                               aDatObj->SetDatumTargetWidth(aVal);
2248                           }
2249                         }
2250                       }
2251                     }
2252                   }
2253                 }
2254               }
2255             }
2256           }
2257         }
2258       }
2259     }
2260     else
2261     {
2262       //processing for darum feature
2263       TDF_Label aDatL = aDGTTool->AddDatum();
2264       aDat = XCAFDoc_Datum::Set(aDatL);
2265       aDGTTool->SetDatum(aShL, aDatL);
2266       aDatObj = aDat->GetObject();
2267       aDatObj->SetName(theDat->Identification());
2268       aDatObj->SetPosition (thePositionCounter);
2269       if(!aXCAFModifiers.IsEmpty())
2270         aDatObj->SetModifiers(aXCAFModifiers);
2271       if (aXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None) 
2272         aDatObj->SetModifierWithValue(aXCAFModifWithVal, aModifValue);
2273       aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2274     }
2275     if(!aDatObj.IsNull()) {
2276       readAnnotation(aTR, aSAR->RelatingShapeAspect(), aDatObj);
2277       aDat->SetObject(aDatObj);
2278     }
2279   }
2280   return !aDat.IsNull();
2281 }
2282
2283
2284 //=======================================================================
2285 //function : ReadDatums
2286 //purpose  : auxilary
2287 //=======================================================================
2288 static Standard_Boolean readDatumsAP242(const Handle(Standard_Transient)& theEnt,
2289                                         const TDF_Label theGDTL,
2290                                         const Handle(TDocStd_Document)& theDoc,
2291                                         const Handle(XSControl_WorkSession)& theWS)
2292 {
2293   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2294   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2295   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2296   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2297   const Interface_Graph& aGraph = aTP->Graph();
2298
2299   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2300   for(anIter.Start(); anIter.More(); anIter.Next()) {
2301     Handle(Standard_Transient) anAtr = anIter.Value();
2302     if(anAtr->IsKind(STANDARD_TYPE(StepDimTol_DatumSystem)))
2303     {
2304       Standard_Integer aPositionCounter = 0;//position on frame 
2305       Handle(StepDimTol_DatumSystem) aDS = Handle(StepDimTol_DatumSystem)::DownCast(anAtr);
2306       Interface_EntityIterator anIterDS = aGraph.Sharings(aDS);
2307       for(anIterDS.Start(); anIterDS.More(); anIterDS.Next()) {
2308         Handle(Standard_Transient) anAtrDS = anIterDS.Value();
2309         if(anAtrDS->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2310         {
2311           //get axis
2312           Handle(StepAP242_GeometricItemSpecificUsage)aAxGISUI
2313             = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anAtrDS);
2314           if (aAxGISUI->IdentifiedItemValue(1)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2315           {
2316             Handle(StepGeom_Axis2Placement3d) anAx
2317               = Handle(StepGeom_Axis2Placement3d)::DownCast(aAxGISUI->IdentifiedItemValue(1));
2318             Handle(XCAFDoc_GeomTolerance) aTol;
2319             if(theGDTL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aTol))
2320             {
2321               Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aTol->GetObject();
2322               Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2323               Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2324               Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2325               gp_Dir aDir;
2326               gp_Dir aDirR;
2327               gp_Pnt aPnt;
2328               if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2329                 !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2330                 !aLocArr.IsNull() && aLocArr->Length() > 2)
2331               {
2332                 aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2333                 aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2334                 aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2335                 gp_Ax2 anA(aPnt, aDir, aDirR);
2336                 anObj->SetAxis(anA);
2337                 aTol->SetObject(anObj);
2338               }
2339             }
2340           }
2341         }
2342       }
2343       if (aDS->NbConstituents() > 0)
2344       {
2345         //get datum feature and datum target from datum system
2346         Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aDRCA = aDS->Constituents();
2347         if(!aDRCA.IsNull())
2348         {
2349           for(Standard_Integer i = aDRCA->Lower(); i <= aDRCA->Upper(); i++)
2350           {
2351             Handle(StepDimTol_DatumReferenceCompartment) aDRC = aDRCA->Value(i);
2352             //gete modifiers
2353             Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModif = aDRC->Modifiers();
2354             XCAFDimTolObjects_DatumModifiersSequence aXCAFModifiers;
2355             XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal = XCAFDimTolObjects_DatumModifWithValue_None;
2356             Standard_Real aModifValue = 0;
2357             if(!aModif.IsNull())
2358             {
2359               for(Standard_Integer m = aModif->Lower(); m <= aModif->Upper(); m++)
2360               {
2361                 if(aModif->Value(m).CaseNumber() == 2)
2362                   aXCAFModifiers.Append(
2363                   (XCAFDimTolObjects_DatumSingleModif)aModif->Value(m).
2364                   SimpleDatumReferenceModifierMember()->Value());
2365                 else if (aModif->Value(m).CaseNumber() == 1)
2366                 {
2367                   aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModif->Value(m).DatumReferenceModifierWithValue()->ModifierType() + 1);
2368                   Standard_Real aVal = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2369                   StepBasic_Unit anUnit = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2370                   Standard_Real aFact=1.;
2371                   if(anUnit.IsNull()) continue;
2372                   if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2373                   Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2374                   if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2375                   aModifValue = aVal;
2376                 }
2377               }
2378             }
2379             aPositionCounter++;
2380             Interface_EntityIterator anIterDRC = aGraph.Shareds(aDRC);
2381             for(anIterDRC.Start(); anIterDRC.More(); anIterDRC.Next()) {
2382               
2383               if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2384               {
2385                 Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRC.Value());
2386                 setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2387               }
2388               else if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_DatumReferenceElement)))
2389               {
2390                 Handle(StepDimTol_DatumReferenceElement) aDRE 
2391                   = Handle(StepDimTol_DatumReferenceElement)::DownCast(anIterDRC.Value());
2392                 //get modifiers from group of datums
2393                 Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifE = aDRE->Modifiers();
2394                 if(!aModifE.IsNull())
2395                 {
2396                   for(Standard_Integer k = aModifE->Lower(); k <= aModifE->Upper(); k++)
2397                   {
2398                     if(aModifE->Value(k).CaseNumber() == 1)
2399                       aXCAFModifiers.Append(
2400                       (XCAFDimTolObjects_DatumSingleModif)aModifE->Value(k).
2401                       SimpleDatumReferenceModifierMember()->Value());
2402                     else if (aModifE->Value(k).CaseNumber() == 2)
2403                     {
2404                       aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierType() + 1);
2405                       Standard_Real aVal = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2406                       StepBasic_Unit anUnit = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2407                       Standard_Real aFact=1.;
2408                       if(anUnit.IsNull()) continue;
2409                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2410                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2411                       if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2412                       aModifValue = aVal;
2413                     }
2414                   }
2415                 }
2416                 Interface_EntityIterator anIterDRE = aGraph.Shareds(aDRE);
2417                 for(anIterDRE.Start(); anIterDRE.More(); anIterDRE.Next()) {
2418                   if(anIterDRE.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2419                   {
2420                     Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRE.Value());
2421                     setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2422                   }
2423                 }
2424               }
2425             }
2426           }
2427         }
2428       }
2429     }
2430   }
2431   return Standard_True;
2432 }
2433
2434 //=======================================================================
2435 //function : craeteGeomTolObjectInXCAF
2436 //purpose  : 
2437 //=======================================================================
2438 static TDF_Label createGDTObjectInXCAF(const Handle(Standard_Transient)& theEnt,
2439                                                const Handle(TDocStd_Document)& theDoc,
2440                                                const Handle(XSControl_WorkSession)& theWS)
2441 {
2442   TDF_Label aGDTL;
2443   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2444      !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) && 
2445      !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2446   {
2447     return aGDTL;
2448   }
2449
2450   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2451   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2452   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2453   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2454   const Interface_Graph& aGraph = aTP->Graph();
2455   Standard_Boolean isAllAround = Standard_False;
2456   Standard_Boolean isAllOver = Standard_False;
2457   
2458   // find RepresentationItem for current Ent
2459   NCollection_Sequence<Handle(Standard_Transient)> aSeqRI1, aSeqRI2;
2460
2461   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2462   for(anIter.Start(); anIter.More(); anIter.Next()) {
2463     Handle(Standard_Transient) anAtr = anIter.Value();
2464     NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2465     if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)))
2466     {
2467       //if associating tolerances with part (All-Over)
2468       Interface_EntityIterator anIterSDR = aGraph.Sharings(anAtr);
2469       for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) 
2470       {
2471         Handle(Standard_Transient) anAtrSDR = anIterSDR.Value();
2472         if(anAtrSDR->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2473         {
2474           isAllOver = Standard_True;
2475           Interface_EntityIterator anIterABSR = aGraph.Shareds(anAtrSDR);
2476           for(anIterABSR.Start(); anIterABSR.More(); anIterABSR.Next()) 
2477           {
2478             Handle(Standard_Transient) anAtrABSR = anIterABSR.Value();
2479             if(anAtrABSR->IsKind(STANDARD_TYPE(StepShape_AdvancedBrepShapeRepresentation)))
2480             {
2481               aSeqRI1.Append(anAtrABSR);
2482             }
2483           }
2484         }
2485       }
2486     }
2487     else if(anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) || 
2488       anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2489     {
2490       //if tolerance attached to dimension
2491       Interface_EntityIterator anIterDim = aGraph.Shareds(anAtr);
2492       for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) 
2493       {
2494         Handle(Standard_Transient) anAtrDim = anIterDim.Value();
2495         if(anAtrDim->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2496           anAtrDim->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2497         {
2498           Interface_EntityIterator anIterCSA = aGraph.Sharings(anAtrDim);
2499           for(anIterCSA.Start(); anIterCSA.More(); anIterCSA.Next()) {
2500             if (anIterCSA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2501               Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterCSA.Value());
2502               for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2503                 if (anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))){
2504                   aSAs.Append(Handle(StepRepr_ShapeAspect)::DownCast(anIterSAR.Value()));
2505                 }
2506               }
2507             }
2508           }
2509         }
2510         else if(anAtrDim->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2511         {
2512           aSAs.Append( Handle(StepRepr_ShapeAspect)::DownCast(anAtrDim));
2513         }
2514       }
2515     }
2516     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2517       anAtr->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2518     {
2519       //processing for composite entity
2520       Handle(Standard_Transient) anAtrTmp = anAtr;
2521       if(anAtr->IsKind(STANDARD_TYPE(StepRepr_AllAroundShapeAspect)))
2522       {
2523         // if applyed AllAround Modifier
2524         isAllAround = Standard_True;
2525         Interface_EntityIterator anIterAASA = aGraph.Sharings(anAtrTmp);
2526         for(anIterAASA.Start(); anIterAASA.More(); anIterAASA.Next()) {
2527           if (anIterAASA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2528             Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterAASA.Value());
2529             for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2530               if ((anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2531                 anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp))) &&
2532                 anAtrTmp != anIterSAR.Value()){
2533                   anAtrTmp = anIterSAR.Value();
2534                   break;
2535               }
2536             }
2537           }
2538         }
2539       }
2540       Interface_EntityIterator anIterCSA = aGraph.Sharings(anAtrTmp);
2541       for(anIterCSA.Start(); anIterCSA.More(); anIterCSA.Next()) {
2542         if (anIterCSA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2543           Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterCSA.Value());
2544           for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2545             if (anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))){
2546               aSAs.Append(Handle(StepRepr_ShapeAspect)::DownCast(anIterSAR.Value()));
2547             }
2548           }
2549         }
2550       }
2551     }
2552     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2553     {
2554       //default
2555       aSAs.Append( Handle(StepRepr_ShapeAspect)::DownCast(anAtr));
2556     }
2557     if(!aSAs.IsEmpty())
2558     {
2559       //get representation items
2560       NCollection_Sequence<Handle(Standard_Transient)> aSeqRI;
2561       for(Standard_Integer i = aSAs.Lower(); i <= aSAs.Upper(); i++)
2562       {
2563         Interface_EntityIterator anIterSA = aGraph.Sharings(aSAs.Value(i));
2564         Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2565         Handle(StepRepr_PropertyDefinition) PropD;
2566         for(anIterSA.Start(); anIterSA.More() && aGISU.IsNull() && PropD.IsNull(); anIterSA.Next()) {
2567           aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2568           PropD = Handle(StepRepr_PropertyDefinition)::DownCast(anIterSA.Value());
2569         }
2570         if(!PropD.IsNull())//for old version
2571         {
2572           Handle(StepRepr_RepresentationItem) RI;
2573           Interface_EntityIterator subs4 = aGraph.Sharings(PropD);
2574           for(subs4.Start(); subs4.More(); subs4.Next()) {
2575             Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2576               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
2577             if(!SDR.IsNull()) {
2578               Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2579               if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2580                 RI = Repr->ItemsValue(1);
2581               }
2582             }
2583           }
2584           if(RI.IsNull()) continue;
2585
2586           if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2587             // read dimensions
2588             Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
2589             if(EC.IsNull()) continue;
2590             Handle(TCollection_HAsciiString) aName;
2591             Handle(StepShape_DimensionalSize) DimSize = 
2592               Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2593             Standard_Real dim1=-1.,dim2=-1.;
2594             subs4 = aGraph.Sharings(DimSize);
2595             for(subs4.Start(); subs4.More(); subs4.Next()) {
2596               Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR = 
2597                 Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
2598               if(!DimCharR.IsNull()) {
2599                 Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
2600                 if(!SDimR.IsNull() && SDimR->NbItems()>0) {
2601                   Handle(StepRepr_RepresentationItem) anItem = SDimR->ItemsValue(1);
2602                   Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(anItem);
2603                   if(!VR.IsNull()) {
2604                     aName = VR->Name();
2605                     //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
2606                     //if(CID.IsNull()) continue;
2607                     //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
2608                     //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
2609                     //if(CIDM.IsNull()) continue;
2610                     //if(CIDM->ArrTransient().IsNull()) continue;
2611                     //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
2612                     //if(CID.CaseMem(CIDM)==1)
2613                     //  HARI = CID.ListRepresentationItem();
2614                     //if(CID.CaseMem(CIDM)==2)
2615                     //  HARI = CID.SetRepresentationItem();
2616                     Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
2617                     if(HARI.IsNull()) continue;
2618                     if(HARI->Length()>0) {
2619                       Handle(StepRepr_RepresentationItem) RI1 = HARI->Value(1);
2620                       if(RI1.IsNull()) continue;
2621                       if(RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2622                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2623                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
2624                         dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2625                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2626                         Standard_Real afact=1.;
2627                         if(anUnit.IsNull()) continue;
2628                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2629                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2630                         if(GetLengthConversionFactor(NU,afact)) dim1=dim1*afact;
2631                       }
2632                     }
2633                     if(HARI->Length()>1) {
2634                       Handle(StepRepr_RepresentationItem) RI2 = HARI->Value(2);
2635                       if(RI2.IsNull()) continue;
2636                       if(RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2637                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2638                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
2639                         dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2640                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2641                         Standard_Real afact=1.;
2642                         if(anUnit.IsNull()) continue;
2643                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2644                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2645                         if(GetLengthConversionFactor(NU,afact)) dim2 = dim2*afact;
2646                       }
2647                     }
2648                   }
2649                 }
2650               }
2651             }
2652             if(dim1<0) continue;
2653             if(dim2<0) dim2=dim1;
2654             //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
2655             // now we know edge_curve and value range therefore
2656             // we can create corresponding D&GT labels
2657             Standard_Integer index = aTP->MapIndex(EC);
2658             TopoDS_Shape aSh;
2659             if(index >0) {
2660               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2661               aSh = TransferBRep::ShapeResult(binder);
2662             }
2663             if(aSh.IsNull()) continue; 
2664             TDF_Label shL;
2665             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2666             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,2);
2667             arr->SetValue(1,dim1);
2668             arr->SetValue(2,dim2);
2669             aDGTTool->SetDimTol(shL,1,arr,aName,DimSize->Name());
2670           }
2671           // read tolerances and datums
2672           else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2673             Handle(StepDimTol_GeometricTolerance) GT =
2674               Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2675             // read common data for tolerance
2676             //Standard_Real dim = GT->Magnitude()->ValueComponent();
2677             Handle (StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
2678             if(dim3.IsNull()) continue;
2679             Standard_Real dim = dim3->ValueComponent();
2680             StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
2681             Standard_Real afact=1.;
2682             if(anUnit.IsNull()) continue;
2683             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2684             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2685             if(GetLengthConversionFactor(NU,afact)) dim = dim*afact;
2686             //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
2687             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,1);
2688             arr->SetValue(1,dim);
2689             Handle(TCollection_HAsciiString) aName = GT->Name();
2690             Handle(TCollection_HAsciiString) aDescription = GT->Description();
2691             Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2692             if(AF.IsNull()) continue;
2693             Standard_Integer index = aTP->MapIndex(AF);
2694             TopoDS_Shape aSh;
2695             if(index >0) {
2696               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2697               aSh = TransferBRep::ShapeResult(binder);
2698             }
2699             if(aSh.IsNull()) continue; 
2700             TDF_Label shL;
2701             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2702             // read specific data for tolerance
2703             if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
2704               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2705                 Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(theEnt);
2706               Standard_Integer kind=20;
2707               Handle(StepDimTol_ModifiedGeometricTolerance) MGT = 
2708                 GTComplex->GetModifiedGeometricTolerance();
2709               if(!MGT.IsNull()) {
2710                 kind = kind + MGT->Modifier()+1;
2711               }
2712               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2713               // translate datums connected with this tolerance
2714               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2715                 GTComplex->GetGeometricToleranceWithDatumReference();
2716               if(!GTWDR.IsNull()) {
2717                 ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2718               }
2719             }
2720             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
2721               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2722                 Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(theEnt);
2723               if(GTWDR.IsNull()) continue;
2724               Standard_Integer kind = 0;
2725               if     (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
2726               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
2727               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
2728               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
2729               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
2730               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
2731               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
2732               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
2733               //cout<<"GTWDR: kind="<<kind<<endl;
2734               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2735               ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2736             }
2737             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
2738               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2739                 Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(theEnt);
2740               Standard_Integer kind = 35 + MGT->Modifier();
2741               aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2742             }
2743             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
2744               aDGTTool->SetDimTol(shL,38,arr,aName,aDescription);
2745             }
2746             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
2747               aDGTTool->SetDimTol(shL,39,arr,aName,aDescription);
2748             }
2749             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
2750               aDGTTool->SetDimTol(shL,40,arr,aName,aDescription);
2751             }
2752             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
2753               aDGTTool->SetDimTol(shL,41,arr,aName,aDescription);
2754             }
2755             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
2756               aDGTTool->SetDimTol(shL,42,arr,aName,aDescription);
2757             }
2758             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
2759               aDGTTool->SetDimTol(shL,43,arr,aName,aDescription);
2760             }
2761             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
2762               aDGTTool->SetDimTol(shL,44,arr,aName,aDescription);
2763             }
2764           }
2765         }
2766         else
2767         {
2768           if(aGISU.IsNull()) continue;
2769           if(aGISU->NbIdentifiedItem() > 0) {
2770             aSeqRI.Append(aGISU->IdentifiedItemValue(1));
2771           }
2772         }
2773       }
2774       if(!aSeqRI.IsEmpty())
2775       {
2776         if(aSeqRI1.IsEmpty())
2777           aSeqRI1 = aSeqRI;
2778         else 
2779           aSeqRI2 = aSeqRI;
2780       }
2781     }
2782   }
2783   if(aSeqRI1.IsEmpty()) return aGDTL;
2784
2785   TDF_LabelSequence aShLS1, aShLS2;
2786
2787   for(Standard_Integer i = aSeqRI1.Lower(); i <= aSeqRI1.Upper() ;i++)
2788   {
2789     Standard_Integer anIndex = aTP->MapIndex(aSeqRI1.Value(i));
2790     TopoDS_Shape aSh;
2791     if(anIndex >0) {
2792       Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2793       aSh = TransferBRep::ShapeResult(aBinder);
2794     }
2795     if(!aSh.IsNull())
2796     {
2797       TDF_Label aShL;
2798       aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2799       aShLS1.Append(aShL);
2800     }
2801   }
2802   if (!aSeqRI2.IsEmpty())
2803   {
2804     //for dimensional location
2805     for(Standard_Integer i = aSeqRI2.Lower(); i <= aSeqRI2.Upper() ;i++)
2806     {
2807       Standard_Integer anIndex = aTP->MapIndex(aSeqRI2.Value(i));
2808       TopoDS_Shape aSh;
2809       if(anIndex >0) {
2810         Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2811         aSh = TransferBRep::ShapeResult(aBinder);
2812       }
2813       if(!aSh.IsNull())
2814       {
2815         TDF_Label aShL;
2816         aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2817         aShLS2.Append(aShL);
2818       }
2819     }
2820   }
2821
2822   if(!aShLS1.IsEmpty())
2823   {
2824     // add to XCAF
2825     if(!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2826     {
2827       aGDTL = aDGTTool->AddDimension();
2828       Handle(XCAFDoc_Dimension) aDim = XCAFDoc_Dimension::Set(aGDTL);
2829       TCollection_AsciiString aStr("DGT:Dimensional_");
2830       if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2831       {
2832         aStr.AssignCat("Size");
2833       }
2834       else if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
2835       {
2836         aStr.AssignCat("Location");
2837       }
2838       TDataStd_Name::Set(aGDTL, aStr);
2839
2840       if(!aShLS2.IsEmpty())
2841       {
2842         aDGTTool->SetDimension(aShLS1, aShLS2, aGDTL);
2843       }
2844       else
2845       {
2846         TDF_LabelSequence aEmptySeq;
2847         aDGTTool->SetDimension(aShLS1, aEmptySeq, aGDTL);
2848       }
2849     }
2850     else
2851     {
2852       aGDTL = aDGTTool->AddGeomTolerance();
2853       Handle(XCAFDoc_GeomTolerance) aGTol = XCAFDoc_GeomTolerance::Set(aGDTL);
2854       TCollection_AsciiString aStr("DGT:GeomTolerance");
2855       TDataStd_Name::Set(aGDTL, aStr);
2856       aDGTTool->SetGeomTolerance(aShLS1, aGDTL);
2857       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aGTol->GetObject();
2858       if(isAllAround)
2859         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Around);
2860       else if(isAllOver)
2861         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Over);
2862       aGTol->SetObject(anObj);
2863     }
2864     readDatumsAP242(theEnt, aGDTL, theDoc, theWS);
2865   }
2866   return aGDTL;
2867 }
2868
2869 //=======================================================================
2870 //function : setDimObjectToXCAF
2871 //purpose  : 
2872 //=======================================================================
2873 static void setDimObjectToXCAF(const Handle(Standard_Transient)& theEnt,
2874                                            const TDF_Label& aDimL,
2875                                            const Handle(TDocStd_Document)& theDoc,
2876                                            const Handle(XSControl_WorkSession)& theWS)
2877 {
2878   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2879   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2880   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2881   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2882   const Interface_Graph& aGraph = aTP->Graph();
2883   Handle(XCAFDimTolObjects_DimensionObject) aDimObj;
2884   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2885     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) 
2886     return;
2887
2888   Handle(StepShape_DimensionalSize) aDimSize = 
2889     Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2890   Handle(StepShape_DimensionalLocation) aDimLocation = 
2891     Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
2892
2893   Standard_Real aDim1=-1.,aDim2=-1.,aDim3=-1.;
2894   Handle(StepShape_TypeQualifier) aTQ;
2895   Handle(StepShape_ValueFormatTypeQualifier) aVFTQ;
2896   Handle(StepShape_ToleranceValue) aTV;
2897   Handle(StepShape_LimitsAndFits) aLAF;
2898   Handle(StepRepr_CompoundRepresentationItem) aCRI;
2899   Handle(StepGeom_Axis2Placement3d) anAP;
2900
2901   Interface_EntityIterator anIterDim;
2902   if(!aDimSize.IsNull())
2903   {
2904     anIterDim = aGraph.Sharings(aDimSize);
2905   }
2906   else
2907   {
2908     anIterDim = aGraph.Sharings(aDimLocation);
2909   }
2910   for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) {
2911     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR = 
2912       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anIterDim.Value());
2913     Handle(StepShape_PlusMinusTolerance) aPMT = 
2914       Handle(StepShape_PlusMinusTolerance)::DownCast(anIterDim.Value());
2915     if(!aDCR.IsNull()) {
2916       Handle(StepShape_ShapeDimensionRepresentation) aSDR = aDCR->Representation();
2917       if(!aSDR.IsNull()) {
2918         Handle(StepRepr_HArray1OfRepresentationItem) aHARI = aSDR->Items();
2919
2920         if(!aHARI.IsNull())
2921         {
2922           for(Standard_Integer nr = aHARI->Lower(); nr <= aHARI->Upper(); nr++)
2923           {
2924             Handle(StepRepr_RepresentationItem) aDRI = aHARI->Value(nr);
2925             if(aDRI.IsNull()) continue;
2926
2927             if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2928               //get values
2929               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aRILMWU =
2930                 Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aDRI);
2931               Standard_Real aVal = aRILMWU->GetMeasureWithUnit()->ValueComponent();
2932               StepBasic_Unit anUnit = aRILMWU->GetMeasureWithUnit()->UnitComponent();
2933               Standard_Real aFact=1.;
2934               if(anUnit.IsNull()) continue;
2935               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2936               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2937               if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2938               if(aDim2 > 0)
2939               {
2940                 if(aDim1 > aDim2)
2941                 {
2942                   Standard_Real aTmp = aDim1;
2943                   aDim1 = aDim2;
2944                   aDim2 = aTmp;
2945                 }
2946                 if(aVal < aDim1)
2947                   aDim1 = aVal;
2948                 else if(aVal > aDim2)
2949                   aDim2 = aVal;
2950               }
2951               else if(aDim1 > 0)
2952               {
2953                 if (aVal > aDim1)
2954                   aDim2 = aVal;
2955                 else
2956                 {
2957                   aDim2 = aDim1;
2958                   aDim1 = aVal;
2959                 }
2960               }
2961               else
2962                 aDim1 = aVal;
2963             }
2964             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit))) {
2965               //get values
2966               Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit) aRIPAMWU =
2967                 Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit)::DownCast(aDRI);
2968               Standard_Real aVal = aRIPAMWU->GetMeasureWithUnit()->ValueComponent();
2969               StepBasic_Unit anUnit = aRIPAMWU->GetMeasureWithUnit()->UnitComponent();
2970               Standard_Real aFact=1.;
2971               if(anUnit.IsNull()) continue;
2972               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2973               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2974               if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
2975               if(aDim2 > 0)
2976               {
2977                 if(aDim1 > aDim2)
2978                 {
2979                   Standard_Real aTmp = aDim1;
2980                   aDim1 = aDim2;
2981                   aDim2 = aTmp;
2982                 }
2983                 if(aVal < aDim1)
2984                   aDim1 = aVal;
2985                 else if(aVal > aDim2)
2986                   aDim2 = aVal;
2987               }
2988               else if(aDim1 > 0)
2989               {
2990                 if (aVal > aDim1)
2991                   aDim2 = aVal;
2992                 else
2993                 {
2994                   aDim2 = aDim1;
2995                   aDim1 = aVal;
2996                 }
2997               }
2998               else
2999                 aDim1 = aVal;
3000             }
3001             else if(aDRI->IsKind(STANDARD_TYPE(StepShape_QualifiedRepresentationItem))) {
3002               //get qualifier
3003               Handle(StepShape_QualifiedRepresentationItem) aQRI =
3004                 Handle(StepShape_QualifiedRepresentationItem)::DownCast(aDRI);
3005               for(Standard_Integer l = 1; l <= aQRI->NbQualifiers(); l++)
3006               {
3007                 aTQ = aQRI->Qualifiers()->Value(l).TypeQualifier();
3008                 aVFTQ = aQRI->Qualifiers()->Value(l).ValueFormatTypeQualifier();
3009               }
3010             }
3011             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_CompoundRepresentationItem))) {
3012               aCRI = Handle(StepRepr_CompoundRepresentationItem)::DownCast(aDRI);
3013             }
3014             else if(aDRI->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
3015             {
3016               anAP = Handle(StepGeom_Axis2Placement3d)::DownCast(aDRI);
3017             }
3018           }
3019         }
3020       }
3021     }
3022     else if (!aPMT.IsNull())
3023     {
3024       StepShape_ToleranceMethodDefinition aTMD = aPMT->Range();
3025       if(aPMT.IsNull()) continue;
3026       if(aTMD.CaseNumber() == 1)
3027         //! 1 -> ToleranceValue from StepShape
3028         //! 2 -> LimitsAndFits from StepShape
3029       {
3030         //plus minus tolerance 
3031         aTV = aTMD.ToleranceValue();
3032         if (aTV.IsNull()) continue;
3033
3034         Standard_Real aVal = aTV->UpperBound()->ValueComponent();
3035         StepBasic_Unit anUnit = aTV->UpperBound()->UnitComponent();
3036         Standard_Real aFact=1.;
3037         if(anUnit.IsNull()) continue;
3038         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3039         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3040         if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
3041         aDim3 = aVal;
3042
3043         aVal = aTV->LowerBound()->ValueComponent();
3044         anUnit = aTV->LowerBound()->UnitComponent();
3045         aFact=1.;
3046         if(anUnit.IsNull()) continue;
3047         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3048         NU = anUnit.NamedUnit();
3049         if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
3050         aDim2 = Abs(aVal);
3051       }
3052       else
3053       {
3054         // calss of tolerance
3055         aLAF = aTMD.LimitsAndFits();
3056       }
3057     }
3058   }
3059
3060   if(aDim1<0) return;
3061
3062   aDimObj = new XCAFDimTolObjects_DimensionObject();
3063   if(aDim2 < 0)
3064     aDimObj->SetValue(aDim1);
3065   else if (aDim3 < 0)
3066   {
3067     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1,2);
3068     anArr->SetValue(1,aDim1);
3069     anArr->SetValue(2,aDim2);
3070     aDimObj->SetValues(anArr);
3071   }
3072   else
3073   {
3074     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1,3);
3075     anArr->SetValue(1,aDim1);
3076     anArr->SetValue(2,aDim2);
3077     anArr->SetValue(3,aDim3);
3078     aDimObj->SetValues(anArr);
3079   }
3080   if(!aTQ.IsNull()) 
3081   {
3082     XCAFDimTolObjects_DimensionQualifier aQ;
3083     if (STEPCAFControl_GDTProperty::GetDimQualifierType(aTQ->Name(), aQ))
3084     {
3085         aDimObj->SetQualifier(aQ);
3086     }
3087   }
3088
3089   if (!aVFTQ.IsNull())
3090   {
3091     //A typical value would be 'NR2 2.2'
3092     TCollection_HAsciiString aFormat = aVFTQ->FormatType();
3093     Standard_Integer i = aFormat.Location(1,' ',1,aFormat.Length());
3094     aFormat.SubString(i+1,i+1)->IntegerValue();
3095     aDimObj->SetNbOfDecimalPlaces(aFormat.SubString(i+1,i+1)->IntegerValue(),
3096       aFormat.SubString(i+3,i+3)->IntegerValue());
3097   }
3098
3099   if (!aLAF.IsNull())
3100   { 
3101     //get class of tolerance
3102     Standard_Boolean aHolle = Standard_False;
3103     XCAFDimTolObjects_DimensionFormVariance aFV = XCAFDimTolObjects_DimensionFormVariance_None;
3104     XCAFDimTolObjects_DimensionGrade aG = XCAFDimTolObjects_DimensionGrade_IT01;
3105     STEPCAFControl_GDTProperty::GetDimClassOfTolerance(aLAF, aHolle, aFV, aG);
3106     aDimObj->SetClassOfTolerance(aHolle, aFV, aG);
3107   }
3108
3109   if (!aCRI.IsNull() && aCRI->ItemElement()->Length() > 0)
3110   {
3111     //get modifiers
3112     XCAFDimTolObjects_DimensionModifiersSequence aModifiers;
3113     STEPCAFControl_GDTProperty::GetDimModifiers(aCRI, aModifiers);
3114     if(aModifiers.Length() > 0)
3115       aDimObj->SetModifiers(aModifiers);
3116   }
3117
3118   Handle(TCollection_HAsciiString) aName;
3119   if(!aDimSize.IsNull())
3120   {
3121     aName = aDimSize->Name();
3122   }
3123   else
3124   {
3125     aName = aDimLocation->Name();
3126   }
3127   XCAFDimTolObjects_DimensionType aType = XCAFDimTolObjects_DimensionType_Location_None;
3128   if (!STEPCAFControl_GDTProperty::GetDimType(aName, aType))
3129   {
3130     if(!aDimSize.IsNull())
3131     {
3132       Handle(StepShape_AngularSize) anAngSize= 
3133         Handle(StepShape_AngularSize)::DownCast(aDimSize);
3134       if(!anAngSize.IsNull())
3135       {
3136         //get qualifier for angular value
3137         aType = XCAFDimTolObjects_DimensionType_Size_Angular;
3138         if(anAngSize->AngleSelection() == StepShape_Equal)
3139           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3140         else if (anAngSize->AngleSelection() == StepShape_Large)
3141           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3142         else if (anAngSize->AngleSelection() == StepShape_Small)
3143           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3144       }
3145     }
3146     else
3147     {
3148       Handle(StepShape_AngularLocation) anAngLoc= 
3149         Handle(StepShape_AngularLocation)::DownCast(aDimLocation);
3150       if(!anAngLoc.IsNull())
3151       {
3152         //get qualifier for angular value
3153         aType = XCAFDimTolObjects_DimensionType_Location_Angular;
3154         if(anAngLoc->AngleSelection() == StepShape_Equal)
3155           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3156         else if (anAngLoc->AngleSelection() == StepShape_Large)
3157           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3158         else if (anAngLoc->AngleSelection() == StepShape_Small)
3159           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3160       }
3161     }
3162     if(aType == XCAFDimTolObjects_DimensionType_Location_None)
3163     {
3164       Handle(StepRepr_ShapeAspect) aPSA;
3165       if(!aDimSize.IsNull())
3166       {
3167         Handle(StepShape_DimensionalSizeWithPath) aDimSizeWithPath= 
3168           Handle(StepShape_DimensionalSizeWithPath)::DownCast(aDimSize);
3169         if (!aDimSizeWithPath.IsNull())
3170         {
3171           aType = XCAFDimTolObjects_DimensionType_Size_WithPath;
3172           aPSA = aDimSizeWithPath->Path();
3173         }
3174       }
3175       else
3176       {
3177         Handle(StepShape_DimensionalLocationWithPath) aDimLocWithPath= 
3178           Handle(StepShape_DimensionalLocationWithPath)::DownCast(aDimLocation);
3179         if (!aDimLocWithPath.IsNull())
3180         {
3181           aType = XCAFDimTolObjects_DimensionType_Location_WithPath;
3182           aPSA = aDimLocWithPath->Path();
3183         }
3184       }
3185
3186       if(!aPSA.IsNull())
3187       {
3188         //for DimensionalLocationWithPath
3189         Handle(StepGeom_GeometricRepresentationItem) aGRI;
3190         Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
3191         Interface_EntityIterator anIterDSWP = aGraph.Sharings(aPSA);
3192         for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
3193           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
3194         }
3195         if(aPGISU.IsNull()) return;
3196         if(aPGISU->NbIdentifiedItem() > 0) {
3197           aGRI = Handle(StepGeom_GeometricRepresentationItem)::DownCast(aPGISU->IdentifiedItemValue(1));
3198         }
3199         if(aGRI.IsNull()) return;
3200         Handle(StepRepr_RepresentationItem) aPRI;
3201         Interface_EntityIterator anIterGRI = aGraph.Sharings(aGRI);
3202         for(anIterGRI.Start(); anIterGRI.More() && aPGISU.IsNull(); anIterGRI.Next()) {
3203           aPRI = Handle(StepRepr_RepresentationItem)::DownCast(anIterGRI.Value());
3204         }
3205         Standard_Integer anIndex = aTP->MapIndex(aPRI);
3206         TopoDS_Edge aSh;
3207         if(anIndex >0) {
3208           Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
3209           aSh = TopoDS::Edge(TransferBRep::ShapeResult(aBinder));
3210         }
3211         if(aSh.IsNull()) return; 
3212         aDimObj->SetPath(aSh);
3213       }
3214       else if(!anAP.IsNull())
3215       {
3216         if(anAP->Name()->String().IsEqual("orientation") && !anAP->Axis().IsNull())
3217         {
3218           //for Oriented Dimensional Location
3219           Handle(TColStd_HArray1OfReal) aDirArr = anAP->RefDirection()->DirectionRatios();
3220           gp_Dir aDir;
3221           if(!aDirArr.IsNull() && aDirArr->Length() > 2)
3222           {
3223             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
3224             aDimObj->SetDirection(aDir);
3225           }
3226           else if(aDirArr->Length() > 1)
3227           {
3228             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, 0);
3229             aDimObj->SetDirection(aDir);
3230           }
3231         }
3232       }
3233     }
3234   }
3235   aDimObj->SetType(aType);
3236
3237   
3238   if(!aDimObj.IsNull())
3239   {
3240
3241     Handle(XCAFDoc_Dimension) aDim;
3242
3243     if(aDimL.FindAttribute(XCAFDoc_Dimension::GetID(),aDim))
3244     {
3245       readAnnotation(aTR, theEnt, aDimObj);
3246       aDim->SetObject(aDimObj);
3247     }
3248   }
3249 }
3250
3251 //=======================================================================
3252 //function : getTolType
3253 //purpose  : 
3254 //=======================================================================
3255 static Standard_Boolean getTolType(const Handle(Standard_Transient)& theEnt,
3256                        XCAFDimTolObjects_GeomToleranceType& theType)
3257 {
3258   if(!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) 
3259     return Standard_False;
3260   theType = XCAFDimTolObjects_GeomToleranceType_None;
3261   if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRef)))
3262   {
3263     Handle(StepDimTol_GeoTolAndGeoTolWthDatRef) anE = Handle(StepDimTol_GeoTolAndGeoTolWthDatRef)::DownCast(theEnt);
3264     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3265   }
3266   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3267   {
3268     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) anE = 
3269       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)::DownCast(theEnt);
3270     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3271   }
3272   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)))
3273   {
3274     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod) anE = 
3275       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)::DownCast(theEnt);
3276     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3277   }
3278   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3279   {
3280     Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) anE = 
3281       Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)::DownCast(theEnt);
3282     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3283   }
3284   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMod)))
3285   {
3286     Handle(StepDimTol_GeoTolAndGeoTolWthMod) anE = 
3287       Handle(StepDimTol_GeoTolAndGeoTolWthMod)::DownCast(theEnt);
3288     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3289   }
3290   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol)))
3291   {
3292     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol) anE = 
3293       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol)::DownCast(theEnt);
3294     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3295   }
3296   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))
3297   {
3298     theType = XCAFDimTolObjects_GeomToleranceType_Angularity;
3299   }
3300   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))
3301   {
3302     theType = XCAFDimTolObjects_GeomToleranceType_CircularRunout;
3303   }
3304   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance)))
3305   {
3306     theType = XCAFDimTolObjects_GeomToleranceType_CircularityOrRoundness;
3307   }
3308   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))
3309   {
3310     theType = XCAFDimTolObjects_GeomToleranceType_Coaxiality;
3311   }
3312   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))
3313   {
3314     theType = XCAFDimTolObjects_GeomToleranceType_Concentricity;
3315   }
3316   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance)))
3317   {
3318     theType = XCAFDimTolObjects_GeomToleranceType_Cylindricity;
3319   }
3320   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance)))
3321   {
3322     theType = XCAFDimTolObjects_GeomToleranceType_Flatness;
3323   }
3324   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))
3325   {
3326     theType = XCAFDimTolObjects_GeomToleranceType_Parallelism;
3327   }
3328   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance)))
3329   {
3330     theType = XCAFDimTolObjects_GeomToleranceType_Perpendicularity;
3331   }
3332   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance)) || 
3333      theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)))
3334   {
3335     theType = XCAFDimTolObjects_GeomToleranceType_Position;
3336   }
3337   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance)))
3338   {
3339     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfLine;
3340   }
3341   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance)))
3342   {
3343     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfSurface;
3344   }
3345   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance)))
3346   {
3347     theType = XCAFDimTolObjects_GeomToleranceType_Straightness;
3348   }
3349   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))
3350   {
3351     theType = XCAFDimTolObjects_GeomToleranceType_Symmetry;
3352   }
3353   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))
3354   {
3355     theType = XCAFDimTolObjects_GeomToleranceType_TotalRunout;
3356   }
3357   return Standard_True;
3358 }
3359 //=======================================================================
3360 //function : setGeomTolObjectToXCAF
3361 //purpose  : 
3362 //=======================================================================
3363 static void setGeomTolObjectToXCAF(const Handle(Standard_Transient)& theEnt,
3364                                            const TDF_Label& theTolL,
3365                                            const Handle(TDocStd_Document)& theDoc,
3366                                            const Handle(XSControl_WorkSession)& theWS)
3367 {
3368   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
3369   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
3370   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
3371   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
3372   const Interface_Graph& aGraph = aTP->Graph();
3373   Handle(XCAFDoc_GeomTolerance) aGTol;
3374   if(!theTolL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aGTol))
3375   {
3376     return;
3377   }
3378   Handle(XCAFDimTolObjects_GeomToleranceObject) aTolObj = aGTol->GetObject();
3379   Handle(StepDimTol_GeometricTolerance) aTolEnt = Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
3380
3381   XCAFDimTolObjects_GeomToleranceType aType = XCAFDimTolObjects_GeomToleranceType_None;
3382   getTolType(theEnt, aType);
3383   aTolObj->SetType(aType);
3384   if(!aTolEnt->Magnitude().IsNull()){
3385     //get value
3386     Standard_Real aVal = aTolEnt->Magnitude()->ValueComponent();
3387     StepBasic_Unit anUnit = aTolEnt->Magnitude()->UnitComponent();
3388     Standard_Real aFact=1.;
3389     if(anUnit.IsNull()) return;
3390     if( !(anUnit.CaseNum(anUnit.Value())==1) ) return;
3391     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3392     if(GetLengthConversionFactor(NU,aFact))
3393       aVal=aVal*aFact;
3394     aTolObj->SetValue(aVal);
3395   }
3396   //get modifiers
3397   XCAFDimTolObjects_GeomToleranceTypeValue aTypeV = XCAFDimTolObjects_GeomToleranceTypeValue_None;
3398   Interface_EntityIterator anIter = aGraph.Sharings(aTolEnt);
3399   for(anIter.Start(); anIter.More(); anIter.Next()) {
3400     if(anIter.Value()->IsKind(STANDARD_TYPE(StepDimTol_ToleranceZone))){
3401       Handle(StepDimTol_ToleranceZoneForm) aForm 
3402                             = Handle(StepDimTol_ToleranceZone)::DownCast(anIter.Value())->Form();
3403       STEPCAFControl_GDTProperty::GetTolValueType(aForm->Name(), aTypeV);
3404       Interface_EntityIterator anIt = aGraph.Sharings(anIter.Value());
3405       for(anIt.Start(); anIt.More(); anIt.Next()) {
3406         if(anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_ProjectedZoneDefinition))){
3407           Handle(StepDimTol_ProjectedZoneDefinition) aPZone
3408                               = Handle(StepDimTol_ProjectedZoneDefinition)::DownCast(anIt.Value());
3409           if(!aPZone->ProjectionLength().IsNull())
3410           {
3411             Standard_Real aVal = aPZone->ProjectionLength()->ValueComponent();
3412             StepBasic_Unit anUnit = aPZone->ProjectionLength()->UnitComponent();
3413             Standard_Real aFact=1.;
3414             if(anUnit.IsNull()) return;
3415             if( !(anUnit.CaseNum(anUnit.Value())==1) ) return;
3416             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3417             if(GetLengthConversionFactor(NU,aFact))
3418               aVal=aVal*aFact;
3419             aTolObj->SetValueOfZoneModifier(aVal);
3420             aTolObj->SetZoneModifier(XCAFDimTolObjects_GeomToleranceZoneModif_Projected);
3421           }
3422         }
3423         else if (anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_RunoutZoneDefinition)))
3424         {
3425           Handle(StepDimTol_RunoutZoneDefinition) aRZone
3426                                 = Handle(StepDimTol_RunoutZoneDefinition)::DownCast(anIt.Value());
3427           if(!aRZone->Orientation().IsNull())
3428           {
3429             Standard_Real aVal = aRZone->Orientation()->Angle()->ValueComponent();
3430             StepBasic_Unit anUnit = aRZone->Orientation()->Angle()->UnitComponent();
3431             Standard_Real aFact=1.;
3432             if(anUnit.IsNull()) continue;
3433             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3434             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3435             if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
3436             aTolObj->SetValueOfZoneModifier(aVal);
3437             aTolObj->SetZoneModifier(XCAFDimTolObjects_GeomToleranceZoneModif_Runout);
3438           }
3439         }
3440       }
3441       aTolObj->SetTypeOfValue(aTypeV);
3442     }
3443   }
3444   Handle(StepDimTol_HArray1OfGeometricToleranceModifier) aModifiers;
3445   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithModifiers)))
3446   {
3447     aModifiers = Handle(StepDimTol_GeometricToleranceWithModifiers)::DownCast(aTolEnt)->Modifiers();
3448   }
3449   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)))
3450   {
3451     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)
3452                             ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3453   }
3454   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMod)))
3455   {
3456     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthMod)
3457                              ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3458   }
3459   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3460   {
3461     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)
3462                              ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3463   }
3464   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3465   {
3466     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)
3467                              ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3468   }
3469   if(!aModifiers.IsNull())
3470   {
3471     for(Standard_Integer i = aModifiers->Lower(); i <= aModifiers->Upper(); i++)
3472     {
3473       if(aModifiers->Value(i) == StepDimTol_GTMLeastMaterialRequirement)
3474         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_L);
3475       else if (aModifiers->Value(i) == StepDimTol_GTMMaximumMaterialRequirement)
3476         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_M);
3477       else
3478         aTolObj->AddModifier((XCAFDimTolObjects_GeomToleranceModif)aModifiers->Value(i));
3479     }
3480   }
3481   Standard_Real aVal = 0;
3482   StepBasic_Unit anUnit;
3483   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithMaximumTolerance)))
3484   {
3485     Handle(StepDimTol_GeometricToleranceWithMaximumTolerance) aMax = Handle(StepDimTol_GeometricToleranceWithMaximumTolerance)::DownCast(aTolEnt);
3486     aVal = aMax->MaximumUpperTolerance()->ValueComponent();
3487     anUnit = aMax->MaximumUpperTolerance()->UnitComponent();
3488   }
3489   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3490   {
3491     Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) aMax = 
3492       Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)::DownCast(aTolEnt);
3493     aVal = aMax->GetMaxTolerance()->ValueComponent();
3494     anUnit = aMax->GetMaxTolerance()->UnitComponent();
3495   }
3496   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3497   {
3498     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) aMax = 
3499       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)::DownCast(aTolEnt);
3500     aVal = aMax->GetMaxTolerance()->ValueComponent();
3501     anUnit = aMax->GetMaxTolerance()->UnitComponent();
3502   }
3503   if (!anUnit.IsNull() && (anUnit.CaseNum(anUnit.Value()) == 1))
3504   {
3505     Standard_Real aFact=1.;
3506     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3507     if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
3508     aTolObj->SetMaxValueModifier(aVal);
3509   }
3510   
3511   readAnnotation(aTR, theEnt, aTolObj);
3512   aGTol->SetObject(aTolObj);
3513 }
3514
3515 //=======================================================================
3516 //function : ReadGDTs
3517 //purpose  : 
3518 //=======================================================================
3519
3520 Standard_Boolean STEPCAFControl_Reader::ReadGDTs(const Handle(XSControl_WorkSession)& theWS,
3521                                                  Handle(TDocStd_Document)& theDoc) const
3522 {
3523   Handle(Interface_InterfaceModel) aModel = theWS->Model();
3524   Handle(StepData_StepModel) aSM = Handle(StepData_StepModel)::DownCast(aModel);
3525   Interface_EntityIterator anI = aSM->Header();
3526   Handle(HeaderSection_FileSchema) aH;
3527   for(anI.Start(); anI.More() && aH.IsNull();anI.Next())
3528     aH = Handle(HeaderSection_FileSchema)::DownCast(anI.Value());
3529   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
3530   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
3531   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
3532   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
3533   if ( aDGTTool.IsNull() ) return Standard_False;
3534
3535   Standard_Integer nb = aModel->NbEntities();
3536   for(Standard_Integer i=1; i<=nb; i++) {
3537     Handle(Standard_Transient) anEnt = aModel->Value(i);
3538     if(anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) || 
3539        anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
3540        anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3541       TDF_Label aGDTL = createGDTObjectInXCAF(anEnt,theDoc,theWS);
3542       if(!aGDTL.IsNull()){
3543         if(anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))){
3544           setGeomTolObjectToXCAF(anEnt, aGDTL,theDoc,theWS);
3545         }
3546         else {
3547           setDimObjectToXCAF(anEnt, aGDTL,theDoc,theWS);
3548         }
3549       }
3550     }
3551   }
3552   return Standard_True;
3553 }
3554
3555
3556 //=======================================================================
3557 //function : FindSolidForPDS
3558 //purpose  : auxilary
3559 //=======================================================================
3560
3561 static Handle(StepShape_SolidModel) FindSolidForPDS(const Handle(StepRepr_ProductDefinitionShape) &PDS,
3562                                                     const Interface_Graph &graph)
3563 {
3564   Handle(StepShape_SolidModel) SM;
3565   Interface_EntityIterator subs = graph.Sharings(PDS);
3566   Handle(StepShape_ShapeRepresentation) SR;
3567   for(subs.Start(); subs.More() && SM.IsNull(); subs.Next()) {
3568     Handle(StepShape_ShapeDefinitionRepresentation) SDR =
3569       Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
3570     if(SDR.IsNull()) continue;
3571     SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
3572     if(SR.IsNull()) continue;
3573     for(Standard_Integer i=1; i<=SR->NbItems() && SM.IsNull(); i++) {
3574       SM = Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(i));
3575     }
3576     if(SM.IsNull()) {
3577       Interface_EntityIterator subs1 = graph.Sharings(SR);
3578       for(subs1.Start(); subs1.More() && SM.IsNull(); subs1.Next()) {
3579         Handle(StepRepr_RepresentationRelationship) RR =
3580           Handle(StepRepr_RepresentationRelationship)::DownCast(subs1.Value());
3581         if(RR.IsNull()) continue;
3582         Handle(StepShape_ShapeRepresentation) SR2;
3583         if(RR->Rep1()==SR) SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep2());
3584         else SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep1());
3585         if(SR2.IsNull()) continue;
3586         for(Standard_Integer i2=1; i2<=SR2->NbItems() && SM.IsNull(); i2++) {
3587           SM = Handle(StepShape_SolidModel)::DownCast(SR2->ItemsValue(i2));
3588         }
3589       }
3590     }
3591   }
3592   return SM;
3593 }
3594
3595
3596 //=======================================================================
3597 //function : ReadMaterials
3598 //purpose  : 
3599 //=======================================================================
3600
3601 Standard_Boolean STEPCAFControl_Reader::ReadMaterials(const Handle(XSControl_WorkSession) &WS,
3602                                                       Handle(TDocStd_Document)& Doc,
3603                                                       const Handle(TColStd_HSequenceOfTransient) &SeqPDS) const
3604 {
3605   Handle(Interface_InterfaceModel) Model = WS->Model();
3606   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
3607   Handle(XSControl_TransferReader) TR = WS->TransferReader();
3608   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
3609   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( Doc->Main() );
3610   if(MatTool.IsNull()) return Standard_False;
3611   
3612   const Interface_Graph& graph = TP->Graph();
3613   for(Standard_Integer i=1; i<=SeqPDS->Length(); i++) {
3614     Handle(StepRepr_ProductDefinitionShape) PDS =
3615       Handle(StepRepr_ProductDefinitionShape)::DownCast(SeqPDS->Value(i));
3616     if(PDS.IsNull()) 
3617       continue;
3618     Handle(StepBasic_ProductDefinition) aProdDef = PDS->Definition().ProductDefinition();
3619     if(aProdDef.IsNull())
3620       continue;
3621     Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString("");
3622     Handle(TCollection_HAsciiString) aDescription = new TCollection_HAsciiString("");
3623     Handle(TCollection_HAsciiString) aDensName = new TCollection_HAsciiString("");
3624     Handle(TCollection_HAsciiString) aDensValType = new TCollection_HAsciiString("");
3625     Standard_Real aDensity=0;
3626     Interface_EntityIterator subs = graph.Sharings( aProdDef);
3627     for(subs.Start(); subs.More(); subs.Next()) {
3628       Handle(StepRepr_PropertyDefinition) PropD =
3629         Handle(StepRepr_PropertyDefinition)::DownCast(subs.Value());
3630       if(PropD.IsNull()) continue;
3631       Interface_EntityIterator subs1 = graph.Sharings(PropD);
3632       for(subs1.Start(); subs1.More(); subs1.Next()) {
3633         Handle(StepRepr_PropertyDefinitionRepresentation) PDR =
3634           Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast(subs1.Value());
3635         if(PDR.IsNull()) continue;
3636         Handle(StepRepr_Representation) Repr = PDR->UsedRepresentation();
3637         if(Repr.IsNull()) continue;
3638         Standard_Integer ir;
3639         for(ir=1; ir<=Repr->NbItems(); ir++) {
3640           Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(ir);
3641           if(RI.IsNull()) continue;
3642           if(RI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
3643             // find name and description for material
3644             Handle(StepRepr_DescriptiveRepresentationItem) DRI =
3645               Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(RI);
3646             aName = DRI->Name();
3647             
3648             aDescription = DRI->Description();
3649             if(aName.IsNull())
3650               aName = aDescription;
3651           }
3652           if(RI->IsKind(STANDARD_TYPE(StepRepr_MeasureRepresentationItem))) {
3653             // try to find density for material
3654             Handle(StepRepr_MeasureRepresentationItem) MRI =
3655               Handle(StepRepr_MeasureRepresentationItem)::DownCast(RI);
3656             aDensity = MRI->Measure()->ValueComponent();
3657             aDensName = MRI->Name();
3658             aDensValType = new TCollection_HAsciiString(MRI->Measure()->ValueComponentMember()->Name());
3659             StepBasic_Unit aUnit = MRI->Measure()->UnitComponent();
3660             if(!aUnit.IsNull()) {
3661               Handle(StepBasic_DerivedUnit) DU = aUnit.DerivedUnit();
3662               if(DU.IsNull()) continue;
3663               for(Standard_Integer idu=1; idu<=DU->NbElements(); idu++) {
3664                 Handle(StepBasic_DerivedUnitElement) DUE = DU->ElementsValue(idu);
3665                 Handle(StepBasic_NamedUnit) NU = DUE->Unit();
3666                 Standard_Real afact=1.;
3667                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit))) {
3668                   if(GetLengthConversionFactor(NU,afact)) aDensity = aDensity/(afact*afact*afact);
3669                   // transfer length value for Density from millimeter to santimeter
3670                   // in order to result density has dimension gram/(sm*sm*sm)
3671                   aDensity = aDensity*1000.;
3672                 }
3673                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit))) {
3674                   if(GetMassConversionFactor(NU,afact)) aDensity=aDensity*afact;
3675                 }
3676               }
3677             }
3678           }
3679         }
3680       }
3681     }
3682    
3683     if( aName.IsNull() || aName->Length()==0 ) 
3684       continue;
3685     // find shape label amd create Material link
3686     TopoDS_Shape aSh;
3687     Handle(StepShape_SolidModel) SM = FindSolidForPDS(PDS,graph);
3688     if(!SM.IsNull()) {
3689       Standard_Integer index = TP->MapIndex(SM);
3690       if(index >0) {
3691         Handle(Transfer_Binder) binder = TP->MapItem(index);
3692         if(!binder.IsNull())
3693           aSh = TransferBRep::ShapeResult(binder);
3694       }
3695     }
3696     if(aSh.IsNull()) continue; 
3697     TDF_Label shL;
3698     if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
3699     MatTool->SetMaterial(shL,aName,aDescription,aDensity,aDensName,aDensValType);
3700   }
3701
3702   return Standard_True;
3703 }
3704
3705 //=======================================================================
3706 //function : SettleShapeData
3707 //purpose  :
3708 //=======================================================================
3709
3710 TDF_Label STEPCAFControl_Reader::SettleShapeData(const Handle(StepRepr_RepresentationItem)& theItem,
3711                                                  TDF_Label& theLab,
3712                                                  const Handle(XCAFDoc_ShapeTool)& theShapeTool,
3713                                                  const Handle(Transfer_TransientProcess)& TP) const
3714 {
3715   TDF_Label aResult = theLab;
3716
3717   Handle(TCollection_HAsciiString) hName = theItem->Name();
3718   if ( hName.IsNull() || hName->IsEmpty() )
3719     return aResult;
3720
3721   Handle(Transfer_Binder) aBinder = TP->Find(theItem);
3722   if ( aBinder.IsNull() )
3723     return aResult;
3724
3725   TopoDS_Shape aShape = TransferBRep::ShapeResult(aBinder);
3726   if ( aShape.IsNull() )
3727     return aResult;
3728
3729   // Allocate sub-Label
3730   aResult = AllocateSubLabel(theLab);
3731
3732   TCollection_AsciiString aName = hName->String();
3733   TDataStd_Name::Set(aResult, aName);
3734   theShapeTool->SetShape(aResult, aShape);
3735
3736   return aResult;
3737 }
3738
3739 //=======================================================================
3740 //function : ExpandSubShapes
3741 //purpose  :
3742 //=======================================================================
3743
3744 void STEPCAFControl_Reader::ExpandSubShapes(const Handle(XCAFDoc_ShapeTool)& ShapeTool,
3745                                             const XCAFDoc_DataMapOfShapeLabel& ShapeLabelMap,
3746                                             const STEPCAFControl_DataMapOfShapePD& ShapePDMap) const
3747 {
3748   const Handle(Transfer_TransientProcess)& TP = Reader().WS()->TransferReader()->TransientProcess();
3749   NCollection_DataMap<TopoDS_Shape, Handle(TCollection_HAsciiString)> ShapeNameMap;
3750   TColStd_MapOfTransient aRepItems;
3751
3752   // Read translation control variables
3753   Standard_Boolean doReadSNames = (Interface_Static::IVal("read.stepcaf.subshapes.name") > 0);
3754
3755   if ( !doReadSNames )
3756     return;
3757
3758   const Interface_Graph& Graph = Reader().WS()->Graph();
3759
3760   for ( STEPCAFControl_DataMapIteratorOfDataMapOfShapePD it(ShapePDMap); it.More(); it.Next() )
3761   {
3762     const TopoDS_Shape& aRootShape = it.Key();
3763     const Handle(StepBasic_ProductDefinition)& aPDef = it.Value();
3764     if ( aPDef.IsNull() )
3765       continue;
3766
3767     // Find SDR by Product
3768     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
3769     Interface_EntityIterator entIt = Graph.TypedSharings( aPDef, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation) );
3770     for ( entIt.Start(); entIt.More(); entIt.Next() )
3771     {
3772       const Handle(Standard_Transient)& aReferer = entIt.Value();
3773       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(aReferer);
3774       if ( !aSDR.IsNull() )
3775         break;
3776     }
3777
3778     if ( aSDR.IsNull() )
3779       continue;
3780
3781     // Access shape representation
3782     Handle(StepShape_ShapeRepresentation)
3783       aShapeRepr = Handle(StepShape_ShapeRepresentation)::DownCast( aSDR->UsedRepresentation() );
3784
3785     if ( aShapeRepr.IsNull() )
3786       continue;
3787
3788     // Access representation items
3789     Handle(StepRepr_HArray1OfRepresentationItem) aReprItems = aShapeRepr->Items();
3790
3791     if ( aReprItems.IsNull() )
3792       continue;
3793
3794     if ( !ShapeLabelMap.IsBound(aRootShape) )
3795       continue;
3796
3797     TDF_Label aRootLab = ShapeLabelMap.Find(aRootShape);
3798
3799     StepRepr_SequenceOfRepresentationItem aMSBSeq;
3800     StepRepr_SequenceOfRepresentationItem aSBSMSeq;
3801
3802     // Iterate over the top level representation items collecting the
3803     // topological containers to expand
3804     for ( Standard_Integer i = aReprItems->Lower(); i <= aReprItems->Upper(); ++i )
3805     {
3806       Handle(StepRepr_RepresentationItem) aTRepr = aReprItems->Value(i);
3807       if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ManifoldSolidBrep) ) )
3808         aMSBSeq.Append(aTRepr);
3809       else if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ShellBasedSurfaceModel) ) )
3810         aSBSMSeq.Append(aTRepr);
3811     }
3812
3813     // Insert intermediate OCAF Labels for SOLIDs in case there are more
3814     // than one Manifold Solid BRep in the Shape Representation
3815     Standard_Boolean doInsertSolidLab = (aMSBSeq.Length() > 1);
3816
3817     // Expand Manifold Solid BReps
3818     for ( Standard_Integer i = 1; i <= aMSBSeq.Length(); ++i )
3819     {
3820       const Handle(StepRepr_RepresentationItem)& aManiRepr = aMSBSeq.Value(i);
3821
3822       // Put additional Label for SOLID
3823       TDF_Label aManiLab;
3824       if ( doInsertSolidLab )
3825         aManiLab = SettleShapeData(aManiRepr, aRootLab, ShapeTool, TP);
3826       else
3827         aManiLab = aRootLab;
3828
3829       ExpandManifoldSolidBrep(aManiLab, aMSBSeq.Value(i), TP, ShapeTool);
3830     }
3831
3832     // Expand Shell-Based Surface Models
3833     for ( Standard_Integer i = 1; i <= aSBSMSeq.Length(); ++i )
3834       ExpandSBSM(aRootLab, aSBSMSeq.Value(i), TP, ShapeTool);
3835   }
3836 }
3837
3838 //=======================================================================
3839 //function : ExpandManifoldSolidBrep
3840 //purpose  :
3841 //=======================================================================
3842
3843 void STEPCAFControl_Reader::ExpandManifoldSolidBrep(TDF_Label& ShapeLab,
3844                                                     const Handle(StepRepr_RepresentationItem)& Repr,
3845                                                     const Handle(Transfer_TransientProcess)& TP,
3846                                                     const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
3847 {
3848   // Access outer shell
3849   Handle(StepShape_ManifoldSolidBrep) aMSB = Handle(StepShape_ManifoldSolidBrep)::DownCast(Repr);
3850   Handle(StepShape_ConnectedFaceSet) aShell = aMSB->Outer();
3851
3852   // Expand shell contents to CAF tree
3853   ExpandShell(aShell, ShapeLab, TP, ShapeTool);
3854 }
3855
3856 //=======================================================================
3857 //function : ExpandSBSM
3858 //purpose  :
3859 //=======================================================================
3860
3861 void STEPCAFControl_Reader::ExpandSBSM(TDF_Label& ShapeLab,
3862                                        const Handle(StepRepr_RepresentationItem)& Repr,
3863                                        const Handle(Transfer_TransientProcess)& TP,
3864                                        const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
3865 {
3866   Handle(StepShape_ShellBasedSurfaceModel) aSBSM = Handle(StepShape_ShellBasedSurfaceModel)::DownCast(Repr);
3867
3868   // Access boundary shells
3869   Handle(StepShape_HArray1OfShell) aShells = aSBSM->SbsmBoundary();
3870   for ( Standard_Integer s = aShells->Lower(); s <= aShells->Upper(); ++s )
3871   {
3872     const StepShape_Shell& aShell = aShells->Value(s);
3873     Handle(StepShape_ConnectedFaceSet) aCFS;
3874     Handle(StepShape_OpenShell) anOpenShell = aShell.OpenShell();
3875     Handle(StepShape_ClosedShell) aClosedShell = aShell.ClosedShell();
3876
3877     if ( !anOpenShell.IsNull() )
3878       aCFS = anOpenShell;
3879     else
3880       aCFS = aClosedShell;
3881
3882     ExpandShell(aCFS, ShapeLab, TP, ShapeTool);
3883   }
3884 }
3885
3886 //=======================================================================
3887 //function : ExpandShell
3888 //purpose  :
3889 //=======================================================================
3890
3891 void STEPCAFControl_Reader::ExpandShell(const Handle(StepShape_ConnectedFaceSet)& Shell,
3892                                         TDF_Label& RootLab,
3893                                         const Handle(Transfer_TransientProcess)& TP,
3894                                         const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
3895 {
3896   // Record CAF data
3897   TDF_Label aShellLab = SettleShapeData(Shell, RootLab, ShapeTool, TP);
3898
3899   // Access faces
3900   Handle(StepShape_HArray1OfFace) aFaces = Shell->CfsFaces();
3901   for ( Standard_Integer f = aFaces->Lower(); f <= aFaces->Upper(); ++f )
3902   {
3903     const Handle(StepShape_Face)& aFace = aFaces->Value(f);
3904
3905     // Record CAF data
3906     TDF_Label aFaceLab = SettleShapeData(aFace, aShellLab, ShapeTool, TP);
3907
3908     // Access face bounds
3909     Handle(StepShape_HArray1OfFaceBound) aWires = aFace->Bounds();
3910     for ( Standard_Integer w = aWires->Lower(); w <= aWires->Upper(); ++w )
3911     {
3912       const Handle(StepShape_Loop)& aWire = aWires->Value(w)->Bound();
3913
3914       // Record CAF data
3915       TDF_Label aWireLab = SettleShapeData(aWire, aFaceLab, ShapeTool, TP);
3916
3917       // Access wire edges
3918       // Currently only EDGE LOOPs are considered (!)
3919       if ( !aWire->IsInstance( STANDARD_TYPE(StepShape_EdgeLoop) ) )
3920         continue;
3921
3922       // Access edges
3923       Handle(StepShape_EdgeLoop) anEdgeLoop = Handle(StepShape_EdgeLoop)::DownCast(aWire);
3924       Handle(StepShape_HArray1OfOrientedEdge) anEdges = anEdgeLoop->EdgeList();
3925       for ( Standard_Integer e = anEdges->Lower(); e <= anEdges->Upper(); ++e )
3926       {
3927         Handle(StepShape_Edge) anEdge = anEdges->Value(e)->EdgeElement();
3928
3929         // Record CAF data
3930         TDF_Label anEdgeLab = SettleShapeData(anEdge, aWireLab, ShapeTool, TP);
3931
3932         // Access vertices
3933         Handle(StepShape_Vertex) aV1 = anEdge->EdgeStart();
3934         Handle(StepShape_Vertex) aV2 = anEdge->EdgeEnd();
3935
3936         // Record CAF data
3937         SettleShapeData(aV1, anEdgeLab, ShapeTool, TP);
3938         SettleShapeData(aV2, anEdgeLab, ShapeTool, TP);
3939       }
3940     }
3941   }
3942 }
3943
3944 //=======================================================================
3945 //function : SetColorMode
3946 //purpose  : 
3947 //=======================================================================
3948
3949 void STEPCAFControl_Reader::SetColorMode (const Standard_Boolean colormode)
3950 {
3951   myColorMode = colormode;
3952 }
3953
3954 //=======================================================================
3955 //function : GetColorMode
3956 //purpose  : 
3957 //=======================================================================
3958
3959 Standard_Boolean STEPCAFControl_Reader::GetColorMode () const
3960 {
3961   return myColorMode;
3962 }
3963
3964 //=======================================================================
3965 //function : SetNameMode
3966 //purpose  : 
3967 //=======================================================================
3968
3969 void STEPCAFControl_Reader::SetNameMode (const Standard_Boolean namemode)
3970 {
3971   myNameMode = namemode;
3972 }
3973
3974 //=======================================================================
3975 //function : GetNameMode
3976 //purpose  : 
3977 //=======================================================================
3978
3979 Standard_Boolean STEPCAFControl_Reader::GetNameMode () const
3980 {
3981   return myNameMode;
3982 }
3983
3984 //=======================================================================
3985 //function : SetLayerMode
3986 //purpose  : 
3987 //=======================================================================
3988
3989 void STEPCAFControl_Reader::SetLayerMode (const Standard_Boolean layermode)
3990 {
3991   myLayerMode = layermode;
3992 }
3993
3994 //=======================================================================
3995 //function : GetLayerMode
3996 //purpose  : 
3997 //=======================================================================
3998
3999 Standard_Boolean STEPCAFControl_Reader::GetLayerMode () const
4000 {
4001   return myLayerMode;
4002 }
4003
4004 //=======================================================================
4005 //function : SetPropsMode
4006 //purpose  : 
4007 //=======================================================================
4008
4009 void STEPCAFControl_Reader::SetPropsMode (const Standard_Boolean propsmode)
4010 {
4011   myPropsMode = propsmode;
4012 }
4013
4014 //=======================================================================
4015 //function : GetPropsMode
4016 //purpose  : 
4017 //=======================================================================
4018
4019 Standard_Boolean STEPCAFControl_Reader::GetPropsMode () const
4020 {
4021   return myPropsMode;
4022 }
4023
4024 //=======================================================================
4025 //function : SetSHUOMode
4026 //purpose  : 
4027 //=======================================================================
4028
4029 void STEPCAFControl_Reader::SetSHUOMode (const Standard_Boolean mode)
4030 {
4031   mySHUOMode = mode;
4032 }
4033
4034 //=======================================================================
4035 //function : GetSHUOMode
4036 //purpose  : 
4037 //=======================================================================
4038
4039 Standard_Boolean STEPCAFControl_Reader::GetSHUOMode () const
4040 {
4041   return mySHUOMode;
4042 }
4043
4044 //=======================================================================
4045 //function : SetGDTMode
4046 //purpose  : 
4047 //=======================================================================
4048
4049 void STEPCAFControl_Reader::SetGDTMode (const Standard_Boolean gdtmode)
4050 {
4051   myGDTMode = gdtmode;
4052 }
4053
4054 //=======================================================================
4055 //function : GetGDTMode
4056 //purpose  : 
4057 //=======================================================================
4058
4059 Standard_Boolean STEPCAFControl_Reader::GetGDTMode () const
4060 {
4061   return myGDTMode;
4062 }
4063
4064
4065 //=======================================================================
4066 //function : SetMatMode
4067 //purpose  : 
4068 //=======================================================================
4069
4070 void STEPCAFControl_Reader::SetMatMode (const Standard_Boolean matmode)
4071 {
4072   myMatMode = matmode;
4073 }
4074
4075 //=======================================================================
4076 //function : GetMatMode
4077 //purpose  : 
4078 //=======================================================================
4079
4080 Standard_Boolean STEPCAFControl_Reader::GetMatMode () const
4081 {
4082   return myMatMode;
4083 }