0029881: Data Exchange - PMI entities ignore length Units
[occt.git] / src / STEPCAFControl / STEPCAFControl_Reader.cxx
1 // Created on: 2000-08-15
2 // Created by: Andrey BETENEV
3 // Copyright (c) 2000-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16
17 #include <BRep_Builder.hxx>
18 #include <Geom_Axis2Placement.hxx>
19 #include <Geom_CartesianPoint.hxx>
20 #include <Geom_Plane.hxx>
21 #include <Interface_EntityIterator.hxx>
22 #include <Interface_InterfaceModel.hxx>
23 #include <StepData_StepModel.hxx>
24 #include <HeaderSection_FileSchema.hxx>
25 #include <Interface_Static.hxx>
26 #include <NCollection_DataMap.hxx>
27 #include <OSD_Path.hxx>
28 #include <Quantity_Color.hxx>
29 #include <StepAP214_AppliedExternalIdentificationAssignment.hxx>
30 #include <StepBasic_ConversionBasedUnitAndLengthUnit.hxx>
31 #include <StepBasic_ConversionBasedUnitAndPlaneAngleUnit.hxx>
32 #include <StepBasic_ConversionBasedUnitAndMassUnit.hxx>
33 #include <StepBasic_DerivedUnit.hxx>
34 #include <StepBasic_DerivedUnitElement.hxx>
35 #include <StepBasic_MeasureValueMember.hxx>
36 #include <StepBasic_MeasureWithUnit.hxx>
37 #include <StepBasic_NamedUnit.hxx>
38 #include <StepBasic_Product.hxx>
39 #include <StepBasic_ProductDefinition.hxx>
40 #include <StepBasic_ProductDefinitionFormation.hxx>
41 #include <StepBasic_ProductDefinitionRelationship.hxx>
42 #include <StepBasic_SiUnit.hxx>
43 #include <StepBasic_SiUnitAndLengthUnit.hxx>
44 #include <StepBasic_Unit.hxx>
45 #include <STEPCAFControl_Controller.hxx>
46 #include <STEPCAFControl_DataMapIteratorOfDataMapOfShapePD.hxx>
47 #include <STEPCAFControl_DataMapOfPDExternFile.hxx>
48 #include <STEPCAFControl_DataMapOfSDRExternFile.hxx>
49 #include <STEPCAFControl_DataMapOfShapePD.hxx>
50 #include <STEPCAFControl_ExternFile.hxx>
51 #include <STEPCAFControl_Reader.hxx>
52 #include <STEPConstruct.hxx>
53 #include <STEPConstruct_Assembly.hxx>
54 #include <STEPConstruct_ExternRefs.hxx>
55 #include <STEPConstruct_Styles.hxx>
56 #include <STEPConstruct_Tool.hxx>
57 #include <STEPConstruct_UnitContext.hxx>
58 #include <STEPConstruct_ValidationProps.hxx>
59 #include <STEPControl_ActorRead.hxx>
60 #include <STEPControl_Reader.hxx>
61 #include <StepGeom_GeometricRepresentationItem.hxx>
62 #include <StepGeom_Axis2Placement3d.hxx>
63 #include <StepGeom_Direction.hxx>
64 #include <StepDimTol_AngularityTolerance.hxx>
65 #include <StepDimTol_CircularRunoutTolerance.hxx>
66 #include <StepDimTol_CoaxialityTolerance.hxx>
67 #include <StepDimTol_ConcentricityTolerance.hxx>
68 #include <StepDimTol_CylindricityTolerance.hxx>
69 #include <StepDimTol_Datum.hxx>
70 #include <StepDimTol_DatumFeature.hxx>
71 #include <StepDimTol_DatumReference.hxx>
72 #include <StepDimTol_DatumReferenceElement.hxx>
73 #include <StepDimTol_DatumReferenceCompartment.hxx>
74 #include <StepDimTol_DatumSystem.hxx>
75 #include <StepDimTol_FlatnessTolerance.hxx>
76 #include <StepDimTol_GeometricTolerance.hxx>
77 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
78 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
79 #include <StepDimTol_GeoTolAndGeoTolWthDatRef.hxx>
80 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol.hxx>
81 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol.hxx>
82 #include <StepDimTol_GeoTolAndGeoTolWthMaxTol.hxx>
83 #include <StepDimTol_HArray1OfDatumReference.hxx>
84 #include <StepDimTol_LineProfileTolerance.hxx>
85 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
86 #include <StepDimTol_ParallelismTolerance.hxx>
87 #include <StepDimTol_PerpendicularityTolerance.hxx>
88 #include <StepDimTol_PositionTolerance.hxx>
89 #include <StepDimTol_ProjectedZoneDefinition.hxx>
90 #include <StepDimTol_RoundnessTolerance.hxx>
91 #include <StepDimTol_RunoutZoneDefinition.hxx>
92 #include <StepDimTol_StraightnessTolerance.hxx>
93 #include <StepDimTol_SurfaceProfileTolerance.hxx>
94 #include <StepDimTol_SymmetryTolerance.hxx>
95 #include <StepDimTol_ToleranceZone.hxx>
96 #include <StepDimTol_ToleranceZoneForm.hxx>
97 #include <StepDimTol_TotalRunoutTolerance.hxx>
98 #include <StepDimTol_GeometricToleranceWithModifiers.hxx>
99 #include <StepDimTol_HArray1OfGeometricToleranceModifier.hxx>
100 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod.hxx>
101 #include <StepDimTol_GeoTolAndGeoTolWthMod.hxx>
102 #include <StepDimTol_GeometricToleranceWithMaximumTolerance.hxx>
103 #include <StepGeom_Axis2Placement3d.hxx>
104 #include <StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext.hxx>
105 #include <StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx.hxx>
106 #include <StepGeom_Plane.hxx>
107 #include <StepGeom_Polyline.hxx>
108 #include <StepDimTol_PlacedDatumTargetFeature.hxx>
109 #include <StepRepr_AssemblyComponentUsage.hxx>
110 #include <StepRepr_CharacterizedDefinition.hxx>
111 #include <StepRepr_CompoundRepresentationItem.hxx>
112 #include <StepRepr_DerivedShapeAspect.hxx>
113 #include <StepRepr_DescriptiveRepresentationItem.hxx>
114 #include <StepRepr_HArray1OfRepresentationItem.hxx>
115 #include <StepRepr_MappedItem.hxx>
116 #include <StepRepr_MeasureRepresentationItem.hxx>
117 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
118 #include <StepRepr_ProductDefinitionShape.hxx>
119 #include <StepRepr_PropertyDefinition.hxx>
120 #include <StepRepr_PropertyDefinitionRepresentation.hxx>
121 #include <StepRepr_Representation.hxx>
122 #include <StepRepr_RepresentationItem.hxx>
123 #include <StepRepr_HArray1OfRepresentationItem.hxx>
124 #include <StepRepr_RepresentationMap.hxx>
125 #include <StepRepr_RepresentationRelationship.hxx>
126 #include <StepRepr_RepresentedDefinition.hxx>
127 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
128 #include <StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI.hxx>
129 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnit.hxx>
130 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI.hxx>
131 #include <StepRepr_SequenceOfRepresentationItem.hxx>
132 #include <StepRepr_ShapeAspect.hxx>
133 #include <StepRepr_ShapeAspectDerivingRelationship.hxx>
134 #include <StepRepr_CompositeShapeAspect.hxx>
135 #include <StepRepr_AllAroundShapeAspect.hxx>
136 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
137 #include <StepRepr_ShapeAspectRelationship.hxx>
138 #include <StepRepr_ShapeRepresentationRelationship.hxx>
139 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
140 #include <StepRepr_ValueRange.hxx>
141 #include <StepRepr_FeatureForDatumTargetRelationship.hxx>
142 #include <StepShape_AdvancedFace.hxx>
143 #include <StepShape_AdvancedBrepShapeRepresentation.hxx>
144 #include <StepShape_AngleRelator.hxx>
145 #include <StepShape_AngularSize.hxx>
146 #include <StepShape_AngularLocation.hxx>
147 #include <StepShape_ClosedShell.hxx>
148 #include <StepShape_ConnectedFaceSet.hxx>
149 #include <StepShape_ContextDependentShapeRepresentation.hxx>
150 #include <StepRepr_CompGroupShAspAndCompShAspAndDatumFeatAndShAsp.hxx>
151 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
152 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
153 #include <StepShape_DimensionalSizeWithPath.hxx>
154 #include <StepShape_DimensionalLocationWithPath.hxx>
155 #include <StepShape_ShapeDimensionRepresentationItem.hxx>
156 #include <StepShape_ShapeRepresentationWithParameters.hxx>
157 #include <StepShape_HArray1OfShapeDimensionRepresentationItem.hxx>
158 #include <StepShape_DimensionalSize.hxx>
159 #include <StepShape_DimensionalLocation.hxx>
160 #include <StepShape_EdgeCurve.hxx>
161 #include <StepShape_EdgeLoop.hxx>
162 #include <StepShape_GeometricCurveSet.hxx>
163 #include <StepShape_GeometricSet.hxx>
164 #include <StepShape_HArray1OfFace.hxx>
165 #include <StepShape_HArray1OfFaceBound.hxx>
166 #include <StepShape_HArray1OfOrientedEdge.hxx>
167 #include <StepShape_HArray1OfShell.hxx>
168 #include <StepShape_LimitsAndFits.hxx>
169 #include <StepShape_Loop.hxx>
170 #include <StepShape_ManifoldSolidBrep.hxx>
171 #include <StepShape_PlusMinusTolerance.hxx>
172 #include <StepShape_QualifiedRepresentationItem.hxx>
173 #include <StepShape_OpenShell.hxx>
174 #include <StepShape_ShapeDefinitionRepresentation.hxx>
175 #include <StepShape_ShapeDimensionRepresentation.hxx>
176 #include <StepShape_ShapeRepresentation.hxx>
177 #include <StepShape_ShellBasedSurfaceModel.hxx>
178 #include <StepShape_SolidModel.hxx>
179 #include <StepShape_ToleranceMethodDefinition.hxx>
180 #include <StepShape_ToleranceValue.hxx>
181 #include <StepShape_ValueFormatTypeQualifier.hxx>
182 #include <StepShape_Vertex.hxx>
183 #include <StepToGeom.hxx>
184 #include <StepVisual_AnnotationCurveOccurrence.hxx>
185 #include <StepVisual_AnnotationFillArea.hxx>
186 #include <StepVisual_AnnotationPlane.hxx>
187 #include <StepVisual_CameraModelD3.hxx>
188 #include <StepVisual_CameraModelD3MultiClipping.hxx>
189 #include <StepVisual_CameraModelD3MultiClippingIntersection.hxx>
190 #include <StepVisual_CameraModelD3MultiClippingUnion.hxx>
191 #include <StepVisual_CoordinatesList.hxx>
192 #include <StepVisual_HArray1OfCameraModelD3MultiClippingInterectionSelect.hxx>
193 #include <StepVisual_HArray1OfCameraModelD3MultiClippingUnionSelect.hxx>
194 #include <StepVisual_DraughtingCallout.hxx>
195 #include <StepVisual_DraughtingCalloutElement.hxx>
196 #include <StepVisual_DraughtingModel.hxx>
197 #include <StepVisual_Invisibility.hxx>
198 #include <StepVisual_LayeredItem.hxx>
199 #include <StepVisual_PlanarBox.hxx>
200 #include <StepVisual_PresentationLayerAssignment.hxx>
201 #include <StepVisual_PresentationStyleByContext.hxx>
202 #include <StepVisual_StyleContextSelect.hxx>
203 #include <StepVisual_StyledItem.hxx>
204 #include <StepVisual_ViewVolume.hxx>
205 #include <StepShape_TypeQualifier.hxx>
206 #include <TCollection_AsciiString.hxx>
207 #include <TCollection_HAsciiString.hxx>
208 #include <TColStd_HArray1OfReal.hxx>
209 #include <TColStd_HArray1OfTransient.hxx>
210 #include <TColStd_HSequenceOfTransient.hxx>
211 #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
212 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
213 #include <TColStd_MapOfTransient.hxx>
214 #include <TColStd_SequenceOfHAsciiString.hxx>
215 #include <TDataStd_Name.hxx>
216 #include <TDataStd_TreeNode.hxx>
217 #include <TDataStd_UAttribute.hxx>
218 #include <TDF_Label.hxx>
219 #include <TDF_Tool.hxx>
220 #include <TDocStd_Document.hxx>
221 #include <TNaming_NamedShape.hxx>
222 #include <TopExp_Explorer.hxx>
223 #include <TopoDS.hxx>
224 #include <TopoDS_Compound.hxx>
225 #include <TopoDS_Iterator.hxx>
226 #include <TopoDS_Shape.hxx>
227 #include <TopTools_ListIteratorOfListOfShape.hxx>
228 #include <TopTools_ListOfShape.hxx>
229 #include <TopTools_MapOfShape.hxx>
230 #include <Transfer_Binder.hxx>
231 #include <Transfer_TransientProcess.hxx>
232 #include <TransferBRep.hxx>
233 #include <UnitsMethods.hxx>
234 #include <XCAFDoc.hxx>
235 #include <XCAFDoc_Area.hxx>
236 #include <XCAFDoc_Centroid.hxx>
237 #include <XCAFDoc_ClippingPlaneTool.hxx>
238 #include <XCAFDoc_ColorTool.hxx>
239 #include <XCAFDoc_DataMapOfShapeLabel.hxx>
240 #include <XCAFDoc_DimTolTool.hxx>
241 #include <XCAFDoc_Dimension.hxx>
242 #include <XCAFDoc_Datum.hxx>
243 #include <XCAFDoc_GeomTolerance.hxx>
244 #include <XCAFDoc_DocumentTool.hxx>
245 #include <XCAFDoc_GraphNode.hxx>
246 #include <XCAFDoc_LayerTool.hxx>
247 #include <XCAFDoc_MaterialTool.hxx>
248 #include <XCAFDoc_ShapeTool.hxx>
249 #include <XCAFDoc_View.hxx>
250 #include <XCAFDoc_ViewTool.hxx>
251 #include <XCAFDoc_Volume.hxx>
252 #include <XCAFDimTolObjects_DimensionModifiersSequence.hxx>
253 #include <XCAFDimTolObjects_GeomToleranceType.hxx>
254 #include <XCAFDimTolObjects_DimensionObject.hxx>
255 #include <XCAFDimTolObjects_GeomToleranceObject.hxx>
256 #include <XCAFDimTolObjects_DatumObject.hxx>
257 #include <XCAFView_Object.hxx>
258 #include <XSAlgo.hxx>
259 #include <XSAlgo_AlgoContainer.hxx>
260 #include <XSControl_TransferReader.hxx>
261 #include <XSControl_WorkSession.hxx>
262 #include <StepAP242_DraughtingModelItemAssociation.hxx>
263 #include <StepAP242_GeometricItemSpecificUsage.hxx>
264 #include <StepGeom_CartesianPoint.hxx>
265 #include <STEPCAFControl_GDTProperty.hxx>
266 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
267 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
268 #include <StepVisual_TessellatedItem.hxx>
269 #include <StepVisual_TessellatedGeometricSet.hxx>
270 #include <StepVisual_TessellatedCurveSet.hxx>
271 #include <StepVisual_CoordinatesList.hxx>
272 #include <NCollection_Vector.hxx>
273
274 #include <TColgp_HArray1OfXYZ.hxx>
275 #include <BRepBuilderAPI_MakeEdge.hxx>
276 #include <BRepTools.hxx>
277 #include <Transfer_ActorOfTransientProcess.hxx>
278 #include <Bnd_Box.hxx>
279 #include <BRepBndLib.hxx>
280
281 // skl 21.08.2003 for reading G&DT
282 //#include <StepRepr_CompoundItemDefinition.hxx>
283 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
284 //#include <StepBasic_ConversionBasedUnit.hxx>
285 //#include <TDataStd_Real.hxx>
286 //#include <TDataStd_Constraint.hxx>
287 //#include <TDataStd_ConstraintEnum.hxx>
288 //#include <TNaming_Tool.hxx>
289 //#include <AIS_InteractiveObject.hxx>
290 //#include <TPrsStd_ConstraintTools.hxx>
291 //#include <AIS_DiameterDimension.hxx>
292 //#include <TPrsStd_Position.hxx>
293 //#include <TPrsStd_AISPresentation.hxx>
294 //#include <TNaming_Builder.hxx>
295 #ifdef OCCT_DEBUG
296 //! Converts address of the passed shape (TShape) to string.
297 //! \param theShape [in] Shape to dump.
298 //! \return corresponding string.
299 TCollection_AsciiString AddrToString(const TopoDS_Shape& theShape)
300 {
301   std::string anAddrStr;
302   std::ostringstream ost;
303   ost << theShape.TShape().get();
304   anAddrStr = ost.str();
305
306   TCollection_AsciiString aStr =
307     TCollection_AsciiString("[").Cat( anAddrStr.c_str() ).Cat("]");
308
309   return aStr;
310 }
311 #endif
312
313 //=======================================================================
314 //function : STEPCAFControl_Reader
315 //purpose  : 
316 //=======================================================================
317
318 STEPCAFControl_Reader::STEPCAFControl_Reader ():
319        myColorMode( Standard_True ),
320        myNameMode ( Standard_True ),
321        myLayerMode( Standard_True ),
322        myPropsMode( Standard_True ),
323            mySHUOMode ( Standard_False ),
324        myGDTMode  ( Standard_True ),
325        myMatMode(Standard_True),
326        myViewMode(Standard_True)
327 {
328   STEPCAFControl_Controller::Init();
329 }
330
331
332 //=======================================================================
333 //function : STEPCAFControl_Reader
334 //purpose  : 
335 //=======================================================================
336
337 STEPCAFControl_Reader::STEPCAFControl_Reader (const Handle(XSControl_WorkSession)& WS,
338                                               const Standard_Boolean scratch) :
339        myColorMode( Standard_True ),
340        myNameMode ( Standard_True ),
341        myLayerMode( Standard_True ),
342        myPropsMode( Standard_True ),
343            mySHUOMode ( Standard_False ),
344        myGDTMode  ( Standard_True ),
345        myMatMode(Standard_True),
346        myViewMode(Standard_True)
347 {
348   STEPCAFControl_Controller::Init();
349   Init ( WS, scratch );
350 }
351
352
353 //=======================================================================
354 //function : Init
355 //purpose  : 
356 //=======================================================================
357
358 void STEPCAFControl_Reader::Init (const Handle(XSControl_WorkSession)& WS,
359                                   const Standard_Boolean scratch)
360 {
361 // necessary only in Writer, to set good actor:  WS->SelectNorm ( "STEP" );
362   myReader.SetWS (WS,scratch);
363   myFiles.Clear();
364 }
365
366
367 //=======================================================================
368 //function : ReadFile
369 //purpose  : 
370 //=======================================================================
371
372 IFSelect_ReturnStatus STEPCAFControl_Reader::ReadFile (const Standard_CString filename)
373 {
374   return myReader.ReadFile ( filename );
375 }
376
377
378 //=======================================================================
379 //function : NbRootsForTransfer
380 //purpose  : 
381 //=======================================================================
382
383 Standard_Integer STEPCAFControl_Reader::NbRootsForTransfer () 
384 {
385   return myReader.NbRootsForTransfer();
386 }
387
388
389 //=======================================================================
390 //function : TransferOneRoot
391 //purpose  : 
392 //=======================================================================
393
394 Standard_Boolean STEPCAFControl_Reader::TransferOneRoot (const Standard_Integer num,
395                                                          Handle(TDocStd_Document) &doc) 
396 {
397   TDF_LabelSequence Lseq;
398   return Transfer ( myReader, num, doc, Lseq );
399 }
400
401
402 //=======================================================================
403 //function : Transfer
404 //purpose  : 
405 //=======================================================================
406
407 Standard_Boolean STEPCAFControl_Reader::Transfer (Handle(TDocStd_Document) &doc)
408 {
409   TDF_LabelSequence Lseq;
410   return Transfer ( myReader, 0, doc, Lseq );
411 }
412
413
414 //=======================================================================
415 //function : Perform
416 //purpose  : 
417 //=======================================================================
418
419 Standard_Boolean STEPCAFControl_Reader::Perform (const Standard_CString filename,
420                                                  Handle(TDocStd_Document) &doc)
421 {
422   if ( ReadFile ( filename ) != IFSelect_RetDone ) return Standard_False;
423   return Transfer ( doc );
424 }
425   
426
427 //=======================================================================
428 //function : Perform
429 //purpose  : 
430 //=======================================================================
431
432 Standard_Boolean STEPCAFControl_Reader::Perform (const TCollection_AsciiString &filename,
433                                                  Handle(TDocStd_Document) &doc)
434 {
435   if ( ReadFile ( filename.ToCString() ) != IFSelect_RetDone ) return Standard_False;
436   return Transfer ( doc );
437 }
438   
439
440 //=======================================================================
441 //function : ExternFiles
442 //purpose  : 
443 //=======================================================================
444
445 const   NCollection_DataMap<TCollection_AsciiString, Handle(STEPCAFControl_ExternFile)>& STEPCAFControl_Reader::ExternFiles () const
446 {
447   return myFiles;
448 }
449         
450
451 //=======================================================================
452 //function : ExternFile
453 //purpose  : 
454 //=======================================================================
455
456 Standard_Boolean STEPCAFControl_Reader::ExternFile (const Standard_CString name,
457                                                     Handle(STEPCAFControl_ExternFile) &ef) const
458 {
459   ef.Nullify();
460   if ( myFiles.IsEmpty() || !myFiles.IsBound ( name ) ) 
461     return Standard_False;
462   ef = myFiles.Find ( name );
463   return Standard_True;
464 }
465
466
467 //=======================================================================
468 //function : Reader
469 //purpose  : 
470 //=======================================================================
471
472 STEPControl_Reader &STEPCAFControl_Reader::ChangeReader () 
473 {
474   return myReader;
475 }
476   
477
478 //=======================================================================
479 //function : Reader
480 //purpose  : 
481 //=======================================================================
482
483 const STEPControl_Reader &STEPCAFControl_Reader::Reader () const
484 {
485   return myReader;
486 }
487   
488
489 //=======================================================================
490 //function : FillShapesMap
491 //purpose  : auxiliary: fill a map by all compounds and their components
492 //=======================================================================
493
494 static void FillShapesMap (const TopoDS_Shape &S, TopTools_MapOfShape &map)
495 {
496   TopoDS_Shape S0 = S;
497   TopLoc_Location loc;
498   S0.Location ( loc );
499   map.Add ( S0 );
500   if ( S.ShapeType() != TopAbs_COMPOUND ) return;
501   for ( TopoDS_Iterator it(S); it.More(); it.Next() ) 
502     FillShapesMap ( it.Value(), map );
503 }
504
505
506 //=======================================================================
507 //function : Transfer
508 //purpose  : basic working method
509 //=======================================================================
510
511 Standard_Boolean STEPCAFControl_Reader::Transfer (STEPControl_Reader &reader,
512                                                   const Standard_Integer nroot,
513                                                   Handle(TDocStd_Document) &doc,
514                                                   TDF_LabelSequence &Lseq,
515                                                   const Standard_Boolean asOne)
516 {
517   reader.ClearShapes();
518   Standard_Integer i;
519   
520   // Read all shapes
521   Standard_Integer num = reader.NbRootsForTransfer();
522   if ( num <=0 ) return Standard_False;
523   if ( nroot ) {
524     if ( nroot > num ) return Standard_False;
525     reader.TransferOneRoot ( nroot );
526   }
527   else {
528     for ( i=1; i <= num; i++ ) reader.TransferOneRoot ( i );
529   }
530   num = reader.NbShapes();
531   if ( num <=0 ) return Standard_False;
532
533   // Fill a map of (top-level) shapes resulting from that transfer
534   // Only these shapes will be considered further
535   TopTools_MapOfShape ShapesMap, NewShapesMap;
536   for ( i=1; i <= num; i++ ) FillShapesMap ( reader.Shape(i), ShapesMap );
537   
538   // Collect information on shapes originating from SDRs
539   // this will be used to distinguish compounds representing assemblies
540   // from the ones representing hybrid models and shape sets
541   STEPCAFControl_DataMapOfShapePD ShapePDMap;
542   STEPCAFControl_DataMapOfPDExternFile PDFileMap;
543   Handle(Interface_InterfaceModel) Model = reader.Model();
544   const Handle(Transfer_TransientProcess) &TP = reader.WS()->TransferReader()->TransientProcess();
545   Standard_Integer nb = Model->NbEntities();
546
547   Handle(TColStd_HSequenceOfTransient) SeqPDS = new TColStd_HSequenceOfTransient;
548
549   for (i = 1; i <= nb; i ++) {
550     Handle(Standard_Transient) enti = Model->Value(i);
551     if(enti->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) {
552       // sequence for acceleration ReadMaterials
553       SeqPDS->Append(enti);
554     }
555     if ( enti->IsKind ( STANDARD_TYPE(StepBasic_ProductDefinition ) ) ) {
556       Handle(StepBasic_ProductDefinition) PD = 
557         Handle(StepBasic_ProductDefinition)::DownCast(enti);
558       Standard_Integer index = TP->MapIndex(PD);
559       if ( index >0 ) {
560         Handle(Transfer_Binder) binder = TP->MapItem (index);
561         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
562         if ( ! S.IsNull() && ShapesMap.Contains(S) ) {
563           NewShapesMap.Add(S);
564           ShapePDMap.Bind ( S, PD ); 
565           Handle(STEPCAFControl_ExternFile) EF;
566           PDFileMap.Bind ( PD, EF );
567         }
568       }
569     }
570     if ( enti->IsKind ( STANDARD_TYPE(StepShape_ShapeRepresentation) ) ) {
571       Standard_Integer index = TP->MapIndex(enti);
572       if ( index >0 ) {
573         Handle(Transfer_Binder) binder = TP->MapItem (index);
574         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
575         if ( ! S.IsNull() && ShapesMap.Contains(S) )
576           NewShapesMap.Add(S);
577       }
578     }
579   }
580
581   // get directory name of the main file
582   OSD_Path mainfile ( reader.WS()->LoadedFile() );
583   mainfile.SetName ( "" );
584   mainfile.SetExtension ( "" );
585   TCollection_AsciiString dpath;
586   mainfile.SystemName ( dpath );
587
588   // Load external references (only for relevant SDRs)
589   // and fill map SDR -> extern file
590   STEPConstruct_ExternRefs ExtRefs ( reader.WS() );
591   ExtRefs.LoadExternRefs();
592   for ( i=1; i <= ExtRefs.NbExternRefs(); i++ ) {
593     // check extern ref format
594     Handle(TCollection_HAsciiString) format = ExtRefs.Format(i);
595     if ( ! format.IsNull() ) {
596       static Handle(TCollection_HAsciiString) ap203 = new TCollection_HAsciiString ( "STEP AP203" );
597       static Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "STEP AP214" );
598       if ( ! format->IsSameString ( ap203, Standard_False ) && 
599            ! format->IsSameString ( ap214, Standard_False ) ) {
600 #ifdef OCCT_DEBUG
601         cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document is neither STEP AP203 nor AP214" << endl;
602 #else
603         continue;
604 #endif
605       }
606     }
607 #ifdef OCCT_DEBUG
608     else cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document format not defined" << endl;
609 #endif
610     
611     // get and check filename of the current extern ref
612     const Standard_CString filename = ExtRefs.FileName(i);
613
614 #ifdef OCCT_DEBUG
615     cout<<"filename="<<filename<<endl;
616 #endif
617
618     if ( ! filename || ! filename[0] ) {
619 #ifdef OCCT_DEBUG
620       cout << "Warning: STEPCAFControl_Reader::Transfer: Extern reference file name is empty" << endl;
621 #endif
622       continue; // not a valid extern ref
623     }
624
625     // compute true path to the extern file
626     TCollection_AsciiString fullname = OSD_Path::AbsolutePath ( dpath, filename );
627     if ( fullname.Length() <= 0 ) fullname = filename;
628
629 /*    
630     char fullname[1024];
631     char *mainfile = reader.WS()->LoadedFile();
632     if ( ! mainfile ) mainfile = "";
633     Standard_Integer slash = 0;
634     for ( Standard_Integer k=0; mainfile[k]; k++ )
635       if ( mainfile[k] == '/' ) slash = k;
636     strncpy ( fullname, mainfile, slash );
637     sprintf ( &fullname[slash], "%s%s", ( mainfile[0] ? "/" : "" ), filename );
638 */
639     
640     // get and check PD associated with the current extern ref
641     Handle(StepBasic_ProductDefinition) PD = ExtRefs.ProdDef(i);
642     if ( PD.IsNull() ) continue; // not a valid extern ref
643     if ( ! PDFileMap.IsBound ( PD ) ) continue; // this PD is not concerned by current transfer
644     
645     // read extern file (or use existing data) and record its data
646     Handle(STEPCAFControl_ExternFile) EF = 
647       ReadExternFile ( filename, fullname.ToCString(), doc );
648     PDFileMap.Bind ( PD, EF );
649   }
650   
651   // and insert them to the document
652   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
653   if ( STool.IsNull() ) return Standard_False;
654   XCAFDoc_DataMapOfShapeLabel map;
655   if ( asOne )
656     Lseq.Append ( AddShape ( reader.OneShape(), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
657   else {
658     for ( i=1; i <= num; i++ ) {
659       Lseq.Append ( AddShape ( reader.Shape(i), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
660     }
661   }
662   
663   // read colors
664   if ( GetColorMode() )
665     ReadColors ( reader.WS(), doc, map );
666   
667   // read names
668   if ( GetNameMode() )
669     ReadNames ( reader.WS(), doc, PDFileMap, map );
670
671   // read validation props
672   if ( GetPropsMode() )
673     ReadValProps ( reader.WS(), doc, PDFileMap, map );
674
675   // read layers
676   if ( GetLayerMode() )
677     ReadLayers ( reader.WS(), doc );
678   
679   // read SHUO entities from STEP model
680   if ( GetSHUOMode() )
681     ReadSHUOs ( reader.WS(), doc, PDFileMap, map );
682
683   // read GDT entities from STEP model
684   if(GetGDTMode())
685     ReadGDTs(reader.WS(),doc);
686
687   // read Material entities from STEP model
688   if(GetMatMode())
689     ReadMaterials(reader.WS(),doc,SeqPDS);
690
691   // read View entities from STEP model
692   if (GetViewMode())
693     ReadViews(reader.WS(), doc);
694
695   // Expand resulting CAF structure for sub-shapes (optionally with their
696   // names) if requested
697   ExpandSubShapes(STool, map, ShapePDMap);
698
699   // Update assembly compounds
700   STool->UpdateAssemblies();
701
702   return Standard_True;
703 }
704
705 //=======================================================================
706 //function : AddShape
707 //purpose  : 
708 //=======================================================================
709
710 TDF_Label STEPCAFControl_Reader::AddShape (const TopoDS_Shape &S, 
711                                            const Handle(XCAFDoc_ShapeTool) &STool,
712                                            const TopTools_MapOfShape &NewShapesMap,
713                                            const STEPCAFControl_DataMapOfShapePD &ShapePDMap,
714                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
715                                            XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
716 {
717   // if shape has already been mapped, just return corresponding label
718   if ( ShapeLabelMap.IsBound ( S ) ) {
719     return ShapeLabelMap.Find ( S );
720   }
721   
722   // if shape is located, create instance
723   if ( ! S.Location().IsIdentity() ) {
724     TopoDS_Shape S0 = S;
725     TopLoc_Location loc;
726     S0.Location ( loc );
727     AddShape ( S0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
728     TDF_Label L = STool->AddShape ( S, Standard_False ); // should create reference
729     ShapeLabelMap.Bind ( S, L );
730     return L;
731   }
732   
733   // if shape is not compound, simple add it
734   if ( S.ShapeType() != TopAbs_COMPOUND ) {
735     TDF_Label L = STool->AddShape ( S, Standard_False );
736     ShapeLabelMap.Bind ( S, L );
737     return L;
738   }
739   
740   // for compounds, compute number of subshapes and check whether this is assembly
741   Standard_Boolean isAssembly = Standard_False;
742   Standard_Integer nbComponents = 0;
743   TopoDS_Iterator it;
744   for ( it.Initialize(S); it.More() && !isAssembly; it.Next(), nbComponents++ ) {
745     TopoDS_Shape Sub0 = it.Value();
746     TopLoc_Location loc;
747     Sub0.Location ( loc );
748     if ( NewShapesMap.Contains ( Sub0 ) ) isAssembly = Standard_True;
749   }
750
751 //  if(nbComponents>0) isAssembly = Standard_True;
752   
753   // check whether it has associated external ref
754   TColStd_SequenceOfHAsciiString SHAS;
755   if ( ShapePDMap.IsBound ( S ) && PDFileMap.IsBound ( ShapePDMap.Find(S) ) ) {
756     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( ShapePDMap.Find(S) );
757     if ( ! EF.IsNull() ) {
758       // (store information on extern refs in the document)
759       SHAS.Append(EF->GetName());
760       // if yes, just return corresponding label
761       if ( ! EF->GetLabel().IsNull() ) {
762         // but if components >0, ignore extern ref!
763         if ( nbComponents <=0 ) {
764           ShapeLabelMap.Bind ( S, EF->GetLabel() );
765           STool->SetExternRefs(EF->GetLabel(),SHAS);
766           return EF->GetLabel();
767         }
768       }
769 #ifdef OCCT_DEBUG
770       if ( ! EF->GetLabel().IsNull() )
771         cout << "Warning: STEPCAFControl_Reader::AddShape: Non-empty shape with external ref; ref is ignored" << endl;
772       else if ( nbComponents <=0 ) 
773         cout << "Warning: STEPCAFControl_Reader::AddShape: Result of reading extern ref is Null" << endl;
774 #endif
775     }
776   }
777   
778   // add compound either as a whole,
779   if ( ! isAssembly ) {
780     TDF_Label L = STool->AddShape ( S, Standard_False );
781     if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
782     ShapeLabelMap.Bind ( S, L );
783     return L;
784   }
785   
786   // or as assembly, component-by-component
787   TDF_Label L = STool->NewShape();
788   nbComponents = 0;
789   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
790     TopoDS_Shape Sub0 = it.Value();
791     TopLoc_Location loc;
792     Sub0.Location ( loc );
793     TDF_Label subL = AddShape ( Sub0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
794     if ( ! subL.IsNull() ) {
795       TDF_Label instL = STool->AddComponent ( L, subL, it.Value().Location() );
796       ShapeLabelMap.Bind(it.Value(), instL);
797     }
798   }
799   if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
800   ShapeLabelMap.Bind ( S, L );
801   //STool->SetShape ( L, S ); // it is necessary for assemblies OCC1747 // commemted by skl for OCC2941
802
803   return L;
804 }
805
806 //=======================================================================
807 //function : ReadExternFile
808 //purpose  : 
809 //=======================================================================
810
811 Handle(STEPCAFControl_ExternFile) STEPCAFControl_Reader::ReadExternFile (const Standard_CString file, 
812                                                                          const Standard_CString fullname, 
813                                                                          Handle(TDocStd_Document)& doc) 
814 {
815   // if the file is already read, associate it with SDR
816   if ( myFiles.IsBound ( file ) ) {
817     return myFiles.ChangeFind ( file );
818   }
819
820 #ifdef OCCT_DEBUG
821   cout << "Reading extern file: " << fullname << endl;
822 #endif
823  
824   // create new WorkSession and Reader
825   Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
826   newWS->SelectNorm ( "STEP" );
827   STEPControl_Reader sr ( newWS, Standard_False );
828   
829   // start to fill the resulting ExternFile structure
830   Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
831   EF->SetWS ( newWS );
832   EF->SetName ( new TCollection_HAsciiString ( file ) );
833   
834   // read file
835   EF->SetLoadStatus ( sr.ReadFile ( fullname ) );
836   
837   // transfer in single-result mode
838   if ( EF->GetLoadStatus() == IFSelect_RetDone ) {
839     TDF_LabelSequence labels;
840     EF->SetTransferStatus ( Transfer ( sr, 0, doc, labels, Standard_True ) );
841     if ( labels.Length() >0 ) EF->SetLabel ( labels.Value(1) );
842   }
843   
844   // add read file to dictionary
845   myFiles.Bind( file, EF );
846   
847   return EF;
848 }
849
850 //=======================================================================
851 //function : findStyledSR
852 //purpose  : auxilary
853 //=======================================================================
854 static void findStyledSR (const Handle(StepVisual_StyledItem) &style,
855                           Handle(StepShape_ShapeRepresentation)& aSR)
856 {
857   // search Shape Represenatation for component styled item
858   for ( Standard_Integer j=1; j <= style->NbStyles(); j++ ) {
859     Handle(StepVisual_PresentationStyleByContext) PSA = 
860       Handle(StepVisual_PresentationStyleByContext)::DownCast(style->StylesValue ( j ));
861     if ( PSA.IsNull() )
862       continue;
863     StepVisual_StyleContextSelect aStyleCntxSlct = PSA->StyleContext();
864     Handle(StepShape_ShapeRepresentation) aCurrentSR = 
865       Handle(StepShape_ShapeRepresentation)::DownCast(aStyleCntxSlct.Representation());
866     if ( aCurrentSR.IsNull() )
867       continue;
868     aSR = aCurrentSR;
869       break;
870   }
871 }
872
873
874 //=======================================================================
875 //function : ReadColors
876 //purpose  : 
877 //=======================================================================
878
879 Standard_Boolean STEPCAFControl_Reader::ReadColors (const Handle(XSControl_WorkSession) &WS,
880                                                     Handle(TDocStd_Document)& Doc,
881                                                     const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
882 {
883   STEPConstruct_Styles Styles ( WS );
884   if ( ! Styles.LoadStyles() ) {
885 #ifdef OCCT_DEBUG
886     cout << "Warning: no styles are found in the model" << endl;
887 #endif
888     return Standard_False;
889   }
890   // searching for invisible items in the model
891   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
892   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
893   
894   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
895   if ( CTool.IsNull() ) return Standard_False;
896   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool(Doc->Main());
897   if (STool.IsNull()) return Standard_False;
898
899   // parse and search for color attributes
900   Standard_Integer nb = Styles.NbStyles();
901   for ( Standard_Integer i=1; i <= nb; i++ ) {
902     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
903     if ( style.IsNull() ) continue;
904     
905     Standard_Boolean IsVisible = Standard_True;
906     // check the visibility of styled item.
907     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
908       if ( style != aHSeqOfInvisStyle->Value( si ) )
909         continue;
910       // found that current style is invisible.
911       IsVisible = Standard_False;
912       break;
913     }
914
915     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
916     // check if it is component style
917     Standard_Boolean IsComponent = Standard_False;
918     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
919       continue;
920     
921     // find shape
922     NCollection_Vector<Handle(Standard_Transient)> anItems;
923     if (!style->Item().IsNull()) {
924       anItems.Append(style->Item());
925     }
926     else if (!style->ItemAP242().Representation().IsNull()){
927       //special case for AP242: item can be Reprsentation
928       Handle(StepRepr_Representation) aRepr = style->ItemAP242().Representation();
929       for (Standard_Integer j = 1; j <= aRepr->Items()->Length(); j++)
930         anItems.Append(aRepr->Items()->Value(j));
931     }
932     for (Standard_Integer itemIt = 0; itemIt < anItems.Length(); itemIt++) {
933       TopoDS_Shape S = STEPConstruct::FindShape ( Styles.TransientProcess(),
934         Handle(StepRepr_RepresentationItem)::DownCast(anItems.Value(itemIt)) );
935       Standard_Boolean isSkipSHUOstyle = Standard_False;
936       // take shape with real location.
937       while ( IsComponent ) {
938         // take SR of NAUO
939         Handle(StepShape_ShapeRepresentation) aSR;
940         findStyledSR( style, aSR );
941         // search for SR along model
942         if (aSR.IsNull())
943           break;
944         Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
945         Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
946         for (subs.Start(); subs.More(); subs.Next()) {
947           aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
948           if ( aSDR.IsNull() )
949             continue;
950           StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
951           Handle(StepRepr_ProductDefinitionShape) PDS = 
952             Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
953           if ( PDS.IsNull() )
954             continue;
955           StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
956           
957           Handle(StepRepr_AssemblyComponentUsage) ACU = 
958             Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
959           if (ACU.IsNull())
960             continue;
961           // PTV 10.02.2003 skip styled item that refer to SHUO
962           if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
963             isSkipSHUOstyle = Standard_True;
964             break;
965           }
966           Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
967             Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
968           if ( NAUO.IsNull() )
969             continue;
970           
971           TopoDS_Shape aSh;
972           // PTV 10.02.2003 to find component of assembly CORRECTLY
973           STEPConstruct_Tool Tool( WS );
974           TDF_Label aShLab = FindInstance ( NAUO, CTool->ShapeTool(), Tool, ShapeLabelMap );
975           aSh = CTool->ShapeTool()->GetShape(aShLab);
976           if (!aSh.IsNull()) {
977             S = aSh;
978             break;
979           }
980         }
981         break;
982       }
983       if (isSkipSHUOstyle)
984         continue; // skip styled item which refer to SHUO
985       
986       if ( S.IsNull() )
987         continue;
988       
989       if (!SurfCol.IsNull() || !BoundCol.IsNull() || !CurveCol.IsNull() || !IsVisible)
990       {
991         TDF_Label aL;
992         Standard_Boolean isFound = STool->SearchUsingMap(S, aL, Standard_False, Standard_True);
993         if (!SurfCol.IsNull() || !BoundCol.IsNull() || !CurveCol.IsNull())
994         {
995           Quantity_Color aSCol, aBCol, aCCol;
996           if (!SurfCol.IsNull())
997             Styles.DecodeColor(SurfCol, aSCol);
998           if (!BoundCol.IsNull())
999             Styles.DecodeColor(BoundCol, aBCol);
1000           if (!CurveCol.IsNull())
1001             Styles.DecodeColor(CurveCol, aCCol);
1002           if (isFound)
1003           {
1004             if (!SurfCol.IsNull())
1005               CTool->SetColor(aL, aSCol, XCAFDoc_ColorSurf);
1006             if (!BoundCol.IsNull())
1007               CTool->SetColor(aL, aBCol, XCAFDoc_ColorCurv);
1008             if (!CurveCol.IsNull())
1009               CTool->SetColor(aL, aCCol, XCAFDoc_ColorCurv);
1010           }
1011           else
1012           {
1013             for (TopoDS_Iterator it(S); it.More(); it.Next())
1014             {
1015               TDF_Label aL1;
1016               if (STool->SearchUsingMap(it.Value(), aL1, Standard_False, Standard_True))
1017               {
1018                 if (!SurfCol.IsNull())
1019                   CTool->SetColor(aL1, aSCol, XCAFDoc_ColorSurf);
1020                 if (!BoundCol.IsNull())
1021                   CTool->SetColor(aL1, aBCol, XCAFDoc_ColorCurv);
1022                 if (!CurveCol.IsNull())
1023                   CTool->SetColor(aL1, aCCol, XCAFDoc_ColorCurv);
1024               }
1025             }
1026           }
1027         }
1028         if (!IsVisible)
1029         {
1030           // sets the invisibility for shape.
1031           if (isFound)
1032             CTool->SetVisibility(aL, Standard_False);
1033         }
1034       }
1035     }
1036   }
1037   CTool->ReverseChainsOfTreeNodes();
1038   return Standard_True;
1039 }
1040
1041 //=======================================================================
1042 //function : GetLabelFromPD
1043 //purpose  : 
1044 //=======================================================================
1045
1046 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1047                                  const Handle(XCAFDoc_ShapeTool) &STool,
1048                                  const Handle(Transfer_TransientProcess) &TP,
1049                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1050                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1051 {
1052   TDF_Label L;
1053   if ( PDFileMap.IsBound ( PD ) ) {
1054     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1055     if ( ! EF.IsNull() ) {
1056       L = EF->GetLabel();
1057       if ( ! L.IsNull() ) return L;
1058     }
1059   }
1060
1061   TopoDS_Shape S;
1062   Handle(Transfer_Binder) binder = TP->Find(PD);
1063   if ( binder.IsNull() || ! binder->HasResult() ) return L;
1064   S = TransferBRep::ShapeResult ( TP, binder );
1065   if ( S.IsNull() ) return L;
1066
1067   if ( ShapeLabelMap.IsBound ( S ) )
1068     L = ShapeLabelMap.Find ( S );
1069   if ( L.IsNull() )
1070     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1071   return L;
1072 }
1073
1074 //=======================================================================
1075 //function : FindInstance
1076 //purpose  : 
1077 //=======================================================================
1078
1079 TDF_Label STEPCAFControl_Reader::FindInstance (const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
1080                                                const Handle(XCAFDoc_ShapeTool) &STool,
1081                                                const STEPConstruct_Tool &Tool,
1082                                                const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1083 {
1084   TDF_Label L;
1085   
1086   // get shape resulting from CDSR (in fact, only location is interesting)
1087   Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
1088   Handle(Transfer_Binder) binder = TP->Find(NAUO);
1089   if ( binder.IsNull() || ! binder->HasResult() ) {
1090 #ifdef OCCT_DEBUG
1091     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1092 #endif
1093     return L;
1094   }
1095   
1096   TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1097   if ( S.IsNull() ) {
1098 #ifdef OCCT_DEBUG
1099     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1100 #endif
1101     return L;
1102   }
1103
1104   if (ShapeLabelMap.IsBound(S))
1105     L = ShapeLabelMap(S);
1106   else
1107     STool->Search(S, L, Standard_True, Standard_True, Standard_False);
1108
1109   return L;
1110 }
1111
1112 //=======================================================================
1113 //function : ReadNames
1114 //purpose  : 
1115 //=======================================================================
1116
1117 Standard_Boolean STEPCAFControl_Reader::ReadNames (const Handle(XSControl_WorkSession) &WS,
1118                                                    Handle(TDocStd_Document)& Doc,
1119                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1120                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1121 {
1122   // get starting data
1123   const Handle(Interface_InterfaceModel) &Model = WS->Model();
1124   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
1125   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
1126   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1127   if ( STool.IsNull() ) return Standard_False;
1128   STEPConstruct_Tool Tool ( WS );
1129
1130   // iterate on model to find all SDRs and CDSRs
1131   Standard_Integer nb = Model->NbEntities();
1132   Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
1133   Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
1134   Handle(TCollection_HAsciiString) name;
1135   TDF_Label L;
1136   for (Standard_Integer i = 1; i <= nb; i++) {
1137     Handle(Standard_Transient) enti = Model->Value(i);
1138
1139     // get description of NAUO
1140     if ( enti->DynamicType() == tNAUO ) {
1141       L.Nullify();
1142       Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
1143         Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
1144       if(NAUO.IsNull()) continue;
1145       Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
1146       for (subs.Start(); subs.More(); subs.Next()) {
1147         Handle(StepRepr_ProductDefinitionShape) PDS = 
1148           Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1149         if(PDS.IsNull()) continue;
1150         Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
1151         if ( PDR.IsNull() ) continue;
1152         if ( PDR->HasDescription() && 
1153             PDR->Description()->UsefullLength() >0 ) name = PDR->Description();
1154         else if ( !PDR->Name().IsNull() && PDR->Name()->UsefullLength() >0 ) name = PDR->Name();
1155         else if ( !PDR->Id().IsNull()) name = PDR->Id();
1156         else name = new TCollection_HAsciiString;
1157       }
1158       // find proper label
1159       L = FindInstance ( NAUO, STool, Tool, ShapeLabelMap );
1160       if ( L.IsNull() ) continue;
1161       TCollection_ExtendedString str ( name->String() );
1162       TDataStd_Name::Set ( L, str );
1163     }
1164
1165     // for PD get name of associated product
1166     if ( enti->DynamicType() == tPD ) {
1167       L.Nullify();
1168       Handle(StepBasic_ProductDefinition) PD = 
1169         Handle(StepBasic_ProductDefinition)::DownCast(enti);
1170       if(PD.IsNull()) continue;
1171       Handle(StepBasic_Product) Prod = (!PD->Formation().IsNull() ? PD->Formation()->OfProduct() : NULL);
1172       if (Prod.IsNull())
1173         name = new TCollection_HAsciiString;
1174       else if (!Prod->Name().IsNull() && Prod->Name()->UsefullLength() > 0) 
1175         name = Prod->Name();
1176       else if (!Prod->Id().IsNull()) 
1177         name = Prod->Id();
1178       else 
1179         name = new TCollection_HAsciiString;
1180       L = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1181       if ( L.IsNull() ) continue;
1182       TCollection_ExtendedString str ( name->String() );
1183       TDataStd_Name::Set ( L, str );
1184     }
1185     // set a name to the document
1186     //TCollection_ExtendedString str ( name->String() );
1187     //TDataStd_Name::Set ( L, str );
1188   }
1189
1190   return Standard_True;
1191 }
1192
1193 //=======================================================================
1194 //function : GetLabelFromPD
1195 //purpose  : 
1196 //=======================================================================
1197
1198 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1199                                  const Handle(XCAFDoc_ShapeTool) &STool,
1200                                  const STEPConstruct_ValidationProps &Props,
1201                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1202                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1203 {
1204   TDF_Label L;
1205   if ( PDFileMap.IsBound ( PD ) ) {
1206     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1207     if ( ! EF.IsNull() ) {
1208       L = EF->GetLabel();
1209       if ( ! L.IsNull() ) return L;
1210     }
1211   }
1212   TopoDS_Shape S = Props.GetPropShape ( PD );
1213   if ( S.IsNull() ) return L;
1214   if ( ShapeLabelMap.IsBound ( S ) )
1215     L = ShapeLabelMap.Find ( S );
1216   if ( L.IsNull() )
1217     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1218   return L;
1219 }
1220
1221 //=======================================================================
1222 //function : ReadValProps
1223 //purpose  : 
1224 //=======================================================================
1225
1226 Standard_Boolean STEPCAFControl_Reader::ReadValProps (const Handle(XSControl_WorkSession) &WS,
1227                                                       Handle(TDocStd_Document)& Doc,
1228                                                       const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1229                                                       const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1230 {
1231   // get starting data
1232   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
1233   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
1234   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1235   if ( STool.IsNull() ) return Standard_False;
1236
1237   // load props from the STEP model
1238   TColStd_SequenceOfTransient props;
1239   STEPConstruct_ValidationProps Props ( WS );
1240   if ( ! Props.LoadProps ( props ) ) {
1241 #ifdef OCCT_DEBUG
1242     cout << "Warning: no validation props found in the model" << endl;
1243 #endif
1244     return Standard_False;
1245   }
1246
1247   // interpret props one by one
1248   for (Standard_Integer i = 1; i <= props.Length(); i ++) {
1249     Handle(StepRepr_PropertyDefinitionRepresentation) PDR = 
1250       Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast ( props.Value(i) );
1251     if ( PDR.IsNull() ) continue;
1252
1253     TDF_Label L;
1254
1255     Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
1256     Interface_EntityIterator subs = Props.Graph().Shareds(PD);
1257     for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
1258       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)) ) {
1259         Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1260         if(PDS.IsNull()) continue;
1261         // find corresponding NAUO
1262         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
1263         Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
1264         for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
1265           if ( subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)) ) 
1266             NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
1267         }
1268         if ( !NAUO.IsNull() ) {
1269           L = FindInstance ( NAUO, STool, WS, ShapeLabelMap );
1270           if ( L.IsNull() ) continue;
1271         }
1272         else {
1273           // find corresponding ProductDefinition:
1274           Handle(StepBasic_ProductDefinition) ProdDef;
1275           Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
1276           for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
1277             if ( subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)) ) 
1278               ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
1279           }
1280           if ( ProdDef.IsNull() ) continue;
1281           L = GetLabelFromPD ( ProdDef, STool, Props, PDFileMap, ShapeLabelMap );
1282         }
1283       }
1284
1285       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)) ) {
1286         Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
1287         if(SA.IsNull()) continue;
1288         // find ShapeRepresentation
1289         Handle(StepShape_ShapeRepresentation) SR;
1290         Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
1291         for(subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
1292           Handle(StepRepr_PropertyDefinition) PropD1 = 
1293             Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
1294           if(PropD1.IsNull()) continue;
1295           Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
1296           for(subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
1297             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1298               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
1299             if(SDR.IsNull()) continue;
1300             SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1301           }
1302         }
1303         if(SR.IsNull()) continue;
1304         Handle(Transfer_Binder) binder;
1305         for(Standard_Integer ir=1; ir<=SR->NbItems() && binder.IsNull(); ir++) {
1306           if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
1307             Handle(StepShape_SolidModel) SM = 
1308               Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
1309             binder = TP->Find(SM);
1310           }
1311           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1312             Handle(StepShape_ShellBasedSurfaceModel) SBSM =
1313               Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
1314             binder = TP->Find(SBSM);
1315           }
1316           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1317             Handle(StepShape_GeometricSet) GS =
1318               Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
1319             binder = TP->Find(GS);
1320           }
1321         }
1322         if ( binder.IsNull() || ! binder->HasResult() ) continue;
1323         TopoDS_Shape S;
1324         S = TransferBRep::ShapeResult ( TP, binder );
1325         if(S.IsNull()) continue;
1326         if ( ShapeLabelMap.IsBound ( S ) )
1327           L = ShapeLabelMap.Find ( S );
1328         if ( L.IsNull() )
1329           STool->Search ( S, L, Standard_True, Standard_True, Standard_True );
1330       }
1331     }
1332
1333     if(L.IsNull()) continue;
1334       
1335     // decode validation properties
1336     Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
1337     for ( Standard_Integer j=1; j <= rep->NbItems(); j++ ) {
1338       Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
1339       Standard_Boolean isArea;
1340       Standard_Real val;
1341       gp_Pnt pos;
1342       if ( Props.GetPropReal ( ent, val, isArea ) ) {
1343         if ( isArea ) XCAFDoc_Area::Set ( L, val );
1344         else XCAFDoc_Volume::Set ( L, val );
1345       }
1346       else if ( Props.GetPropPnt ( ent, rep->ContextOfItems(), pos ) ) {
1347         XCAFDoc_Centroid::Set ( L, pos );
1348       }
1349     }
1350   }
1351   return Standard_True;
1352 }
1353
1354 //=======================================================================
1355 //function : ReadLayers
1356 //purpose  : 
1357 //=======================================================================
1358
1359 Standard_Boolean STEPCAFControl_Reader::ReadLayers (const Handle(XSControl_WorkSession) &WS,
1360                                                     Handle(TDocStd_Document)& Doc) const
1361 {
1362   const Handle(Interface_InterfaceModel) &Model = WS->Model();
1363   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
1364   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
1365   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1366   if ( STool.IsNull() ) return Standard_False;
1367   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( Doc->Main() );
1368   if ( LTool.IsNull() ) return Standard_False;
1369   
1370   Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
1371   Standard_Integer nb = Model->NbEntities();
1372   Handle(TCollection_HAsciiString) name;
1373   
1374   for (Standard_Integer i = 1; i <= nb; i ++) {
1375     Handle(Standard_Transient) enti = Model->Value(i);
1376     if ( ! enti->IsKind ( tSVPLA ) ) continue;
1377     Handle(StepVisual_PresentationLayerAssignment) SVPLA = 
1378       Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
1379     if (SVPLA->AssignedItems().IsNull())
1380       continue;
1381     
1382     Handle(TCollection_HAsciiString) descr = SVPLA->Description();
1383     Handle(TCollection_HAsciiString) hName = SVPLA->Name();
1384     TCollection_ExtendedString aLayerName ( hName->String() );
1385      
1386     // find a target shape and its label in the document
1387     for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++ ) {
1388       StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
1389       Handle(Transfer_Binder) binder = TP->Find( LI.Value() );
1390       if ( binder.IsNull() || ! binder->HasResult() ) continue;
1391       
1392       TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1393       if ( S.IsNull() ) continue;
1394         
1395       TDF_Label shL;
1396       if ( ! STool->Search ( S, shL, Standard_True, Standard_True, Standard_True ) ) continue;
1397       LTool->SetLayer ( shL, aLayerName );
1398     }
1399     
1400     // check invisibility
1401     Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
1402     for (subs.Start(); subs.More(); subs.Next()) {
1403       if ( ! subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility)) ) continue;
1404 #ifdef OCCT_DEBUG
1405       cout<< "\tLayer \"" << aLayerName << "\" is invisible"<<endl;
1406 #endif
1407       //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
1408       TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
1409       Handle(TDataStd_UAttribute) aUAttr;
1410       aUAttr->Set( InvLayerLab, XCAFDoc::InvisibleGUID() );
1411     }
1412   }
1413   return Standard_True;
1414 }
1415
1416 //=======================================================================
1417 //function : ReadSHUOs
1418 //purpose  : 
1419 //=======================================================================
1420
1421 static Standard_Boolean findNextSHUOlevel (const Handle(XSControl_WorkSession) &WS,
1422                                            const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1423                                            const Handle(XCAFDoc_ShapeTool)& STool,
1424                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1425                                            const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1426                                            TDF_LabelSequence& aLabels)
1427 {
1428   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1429   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1430   for (subs.Start(); subs.More(); subs.Next()) {
1431     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1432       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1433       break;
1434     }
1435   }
1436   if (subSHUO.IsNull())
1437     return Standard_False;
1438   
1439   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = subSHUO->NextUsage();
1440   if (NUNAUO.IsNull())
1441     return Standard_False;
1442 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1443 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1444 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1445 //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1446 //   if ( binder.IsNull() || ! binder->HasResult() )
1447 //     return Standard_False;
1448 //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1449   // get label of NAUO next level
1450   TDF_Label NULab;
1451   STEPConstruct_Tool Tool( WS );
1452   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, ShapeLabelMap ); 
1453 //   STool->Search(NUSh, NUlab);
1454   if (NULab.IsNull())
1455     return Standard_False;
1456   aLabels.Append( NULab );
1457   // and check by recurse.
1458   findNextSHUOlevel( WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels );
1459   return Standard_True;
1460 }
1461
1462
1463 //=======================================================================
1464 //function : setSHUOintoDoc
1465 //purpose  : auxilary
1466 //=======================================================================
1467 static TDF_Label setSHUOintoDoc (const Handle(XSControl_WorkSession) &WS,
1468                                  const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1469                                  const Handle(XCAFDoc_ShapeTool)& STool,
1470                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1471                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1472 {
1473   TDF_Label aMainLabel;
1474   // get upper usage NAUO from SHUO.
1475   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1476     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1477   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = SHUO->NextUsage();
1478   if ( UUNAUO.IsNull() || NUNAUO.IsNull() ) {
1479 #ifdef OCCT_DEBUG
1480     cout << "Warning: " << __FILE__ <<": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
1481 #endif
1482     return aMainLabel;
1483   }
1484 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1485 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1486 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1487 //   TopoDS_Shape UUSh, NUSh;
1488 //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1489 //   if ( binder.IsNull() || ! binder->HasResult() )
1490 //     return aMainLabel;
1491 //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1492 //   binder = TP->Find(NUNAUO);
1493 //   if ( binder.IsNull() || ! binder->HasResult() )
1494 //     return aMainLabel;
1495 //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1496
1497   // get first labels for first SHUO attribute
1498   TDF_Label UULab, NULab;
1499   STEPConstruct_Tool Tool( WS );
1500   UULab = STEPCAFControl_Reader::FindInstance ( UUNAUO, STool, Tool, ShapeLabelMap ); 
1501   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, ShapeLabelMap ); 
1502   
1503 //   STool->Search(UUSh, UULab);
1504 //   STool->Search(NUSh, NULab);
1505   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1506   //create sequence fo labels to set SHUO structure into the document
1507   TDF_LabelSequence ShuoLabels;
1508   ShuoLabels.Append( UULab );
1509   ShuoLabels.Append( NULab );
1510   // add all other labels of sub SHUO entities
1511   findNextSHUOlevel( WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels );
1512   // last accord for SHUO
1513   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1514   if ( STool->SetSHUO( ShuoLabels, anSHUOAttr ) )
1515     aMainLabel = anSHUOAttr->Label();
1516   
1517   return aMainLabel;
1518 }
1519
1520
1521 //=======================================================================
1522 //function : ReadSHUOs
1523 //purpose  : 
1524 //=======================================================================
1525
1526 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs (const Handle(XSControl_WorkSession) &WS,
1527                                                    Handle(TDocStd_Document)& Doc,
1528                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1529                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1530 {
1531   // the big part code duplication from ReadColors.
1532   // It is possible to share this code functionality, just to decide how ???
1533   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
1534   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1535   
1536   STEPConstruct_Styles Styles ( WS );
1537   if ( ! Styles.LoadStyles() ) {
1538 #ifdef OCCT_DEBUG
1539     cout << "Warning: no styles are found in the model" << endl;
1540 #endif
1541     return Standard_False;
1542   }
1543   // searching for invisible items in the model
1544   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1545   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
1546   // parse and search for color attributes
1547   Standard_Integer nb = Styles.NbStyles();
1548   for ( Standard_Integer i=1; i <= nb; i++ ) {
1549     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
1550     if ( style.IsNull() ) continue;
1551     
1552     Standard_Boolean IsVisible = Standard_True;
1553     // check the visibility of styled item.
1554     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
1555       if ( style != aHSeqOfInvisStyle->Value( si ) )
1556         continue;
1557       // found that current style is invisible.
1558 #ifdef OCCT_DEBUG
1559       cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
1560 #endif
1561       IsVisible = Standard_False;
1562       break;
1563     }
1564
1565     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
1566     // check if it is component style
1567     Standard_Boolean IsComponent = Standard_False;
1568     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
1569       continue;
1570     if (!IsComponent)
1571       continue;
1572     Handle(StepShape_ShapeRepresentation) aSR;
1573     findStyledSR( style, aSR );
1574     // search for SR along model
1575     if ( aSR.IsNull() )
1576       continue;
1577     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
1578     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1579     for (subs.Start(); subs.More(); subs.Next()) {
1580       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1581       if ( aSDR.IsNull() )
1582         continue;
1583       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1584       Handle(StepRepr_ProductDefinitionShape) PDS = 
1585         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1586       if ( PDS.IsNull() )
1587         continue;
1588       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1589       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1590         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1591       if ( SHUO.IsNull() )
1592         continue;
1593       
1594       // set the SHUO structure to the document
1595       TDF_Label aLabelForStyle = setSHUOintoDoc( WS, SHUO, STool, PDFileMap, ShapeLabelMap );
1596       if ( aLabelForStyle.IsNull() ) {
1597 #ifdef OCCT_DEBUG
1598         cout << "Warning: " << __FILE__ <<": coudnot create SHUO structure in the document" << endl;
1599 #endif
1600         continue;
1601       }
1602       // now set the style to the SHUO main label.
1603       if ( ! SurfCol.IsNull() ) {
1604         Quantity_Color col;
1605         Styles.DecodeColor ( SurfCol, col );
1606         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorSurf );
1607       }
1608       if ( ! BoundCol.IsNull() ) {
1609         Quantity_Color col;
1610         Styles.DecodeColor ( BoundCol, col );
1611         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1612       }
1613       if ( ! CurveCol.IsNull() ) {
1614         Quantity_Color col;
1615         Styles.DecodeColor ( CurveCol, col );
1616         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1617       }
1618       if ( !IsVisible )
1619         // sets the invisibility for shape.
1620         CTool->SetVisibility( aLabelForStyle, Standard_False );
1621       
1622     } // end search SHUO by SDR
1623   } // end iterates on styles
1624       
1625   return Standard_True;
1626 }
1627
1628 //=======================================================================
1629 //function : GetMassConversionFactor
1630 //purpose  : 
1631 //=======================================================================
1632 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1633                                                 Standard_Real& afact)
1634 {
1635   afact=1.;
1636   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit)) ) return Standard_False;
1637   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1638     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1639   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1640   afact = MWUCBU->ValueComponent();
1641   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1642   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1643     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1644     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1645       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1646       if(SU->Name()==StepBasic_sunGram) {
1647         if(SU->HasPrefix())
1648           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1649       }
1650     }
1651   }
1652   return Standard_True;
1653 }
1654
1655 //=======================================================================
1656 //function : readPMIPresentation
1657 //purpose  : read polyline or tessellated presentation for 
1658 // (Annotation_Curve_Occurrence or Draughting_Callout)
1659 //=======================================================================
1660 Standard_Boolean readPMIPresentation(const Handle(Standard_Transient)& thePresentEntity,
1661                                      const Handle(XSControl_TransferReader)& theTR,
1662                                      const Standard_Real theFact,
1663                                      TopoDS_Shape& thePresentation, 
1664                                      Handle(TCollection_HAsciiString)& thePresentName, 
1665                                      Bnd_Box& theBox)
1666 {
1667   if (thePresentEntity.IsNull())
1668     return Standard_False;
1669   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1670   Handle(StepVisual_AnnotationOccurrence) anAO;
1671   NCollection_Vector<Handle(StepVisual_StyledItem)> anAnnotations;
1672   if (thePresentEntity->IsKind(STANDARD_TYPE(StepVisual_AnnotationOccurrence)))
1673   {
1674     anAO = Handle(StepVisual_AnnotationOccurrence)::DownCast(thePresentEntity);
1675     if (!anAO.IsNull()) {
1676       thePresentName = anAO->Name();
1677       anAnnotations.Append(anAO);
1678     }
1679   }
1680   else if (thePresentEntity->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout)))
1681   {
1682     Handle(StepVisual_DraughtingCallout) aDCallout =
1683       Handle(StepVisual_DraughtingCallout)::DownCast(thePresentEntity);
1684     thePresentName = aDCallout->Name();
1685     for (Standard_Integer i = 1; i <= aDCallout->NbContents() && anAO.IsNull(); i++) {
1686       anAO = Handle(StepVisual_AnnotationOccurrence)::DownCast(aDCallout->ContentsValue(i).Value());
1687       if (!anAO.IsNull())
1688       {
1689         anAnnotations.Append(anAO);
1690         continue;
1691       }
1692       Handle(StepVisual_TessellatedAnnotationOccurrence) aTesselation =
1693         aDCallout->ContentsValue(i).TessellatedAnnotationOccurrence();
1694       if (!aTesselation.IsNull())
1695         anAnnotations.Append(aTesselation);
1696     }
1697   }
1698
1699   if (!anAnnotations.Length())
1700     return Standard_False;
1701
1702
1703   BRep_Builder aB;
1704   TopoDS_Compound aResAnnotation;
1705   aB.MakeCompound(aResAnnotation);
1706
1707   Standard_Integer i = 0;
1708   Bnd_Box aBox;
1709   Standard_Integer nbShapes = 0;
1710   for (; i < anAnnotations.Length(); i++)
1711   {
1712     Handle(StepVisual_StyledItem) anItem = anAnnotations(i);
1713     anAO = Handle(StepVisual_AnnotationOccurrence)::DownCast(anItem);
1714     TopoDS_Shape anAnnotationShape;
1715     if (!anAO.IsNull())
1716     {
1717       Handle(StepRepr_RepresentationItem) aCurveItem = anAO->Item();
1718       anAnnotationShape = STEPConstruct::FindShape(aTP, aCurveItem);
1719       if (anAnnotationShape.IsNull())
1720       {
1721         Handle(Transfer_Binder) binder = theTR->Actor()->Transfer(aCurveItem, aTP);
1722         if (!binder.IsNull() && binder->HasResult()) {
1723           anAnnotationShape = TransferBRep::ShapeResult(aTP, binder);
1724         }
1725       }
1726     }
1727     //case of tessellated entities
1728     else
1729     {
1730       Handle(StepRepr_RepresentationItem) aTessItem = anItem->Item();
1731       if (aTessItem.IsNull())
1732         continue;
1733       Handle(StepVisual_TessellatedGeometricSet) aTessSet = Handle(StepVisual_TessellatedGeometricSet)::DownCast(aTessItem);
1734       if (aTessSet.IsNull())
1735         continue;
1736       NCollection_Handle<StepVisual_Array1OfTessellatedItem> aListItems = aTessSet->Items();
1737       Standard_Integer nb = aListItems.IsNull() ? 0 : aListItems->Length();
1738       Handle(StepVisual_TessellatedCurveSet) aTessCurve;
1739       for (Standard_Integer n = 1; n <= nb && aTessCurve.IsNull(); n++)
1740       {
1741         aTessCurve = Handle(StepVisual_TessellatedCurveSet)::DownCast(aListItems->Value(n));
1742       }
1743       if (aTessCurve.IsNull())
1744         continue;
1745       Handle(StepVisual_CoordinatesList) aCoordList = aTessCurve->CoordList();
1746       if (aCoordList.IsNull())
1747         continue;
1748       Handle(TColgp_HArray1OfXYZ)  aPoints = aCoordList->Points();
1749
1750       if (aPoints.IsNull() || aPoints->Length() == 0)
1751         continue;
1752       NCollection_Handle<StepVisual_VectorOfHSequenceOfInteger> aCurves = aTessCurve->Curves();
1753       Standard_Integer aNbC = (aCurves.IsNull() ? 0 : aCurves->Length());
1754       TopoDS_Compound aComp;
1755       aB.MakeCompound(aComp);
1756
1757       Standard_Integer k = 0;
1758       for (; k < aNbC; k++)
1759       {
1760         Handle(TColStd_HSequenceOfInteger) anIndexes = aCurves->Value(k);
1761         TopoDS_Wire aCurW;
1762         aB.MakeWire(aCurW);
1763
1764         for (Standard_Integer n = 1; n < anIndexes->Length(); n++)
1765         {
1766           Standard_Integer ind = anIndexes->Value(n);
1767           Standard_Integer indnext = anIndexes->Value(n + 1);
1768           if (ind > aPoints->Length() || indnext > aPoints->Length())
1769             continue;
1770           gp_Pnt aP1(aPoints->Value(ind) * theFact);
1771           gp_Pnt aP2(aPoints->Value(indnext) * theFact);
1772           BRepBuilderAPI_MakeEdge aMaker(aP1, aP2);
1773           if (aMaker.IsDone())
1774           {
1775             TopoDS_Edge aCurE = aMaker.Edge();
1776             aB.Add(aCurW, aCurE);
1777           }
1778         }
1779         aB.Add(aComp, aCurW);
1780       }
1781       anAnnotationShape = aComp;
1782     }
1783     if (!anAnnotationShape.IsNull())
1784     {
1785       nbShapes++;
1786       aB.Add(aResAnnotation, anAnnotationShape);
1787       if (i == anAnnotations.Length() - 1)
1788         BRepBndLib::AddClose(anAnnotationShape, aBox);
1789     }
1790   }
1791
1792   thePresentation = aResAnnotation;
1793   theBox = aBox;
1794   return (nbShapes > 0);
1795 }
1796
1797 //=======================================================================
1798 //function : readAnnotationPlane
1799 //purpose  : read annotation plane
1800 //=======================================================================
1801 Standard_Boolean readAnnotationPlane(const Handle(StepVisual_AnnotationPlane) theAnnotationPlane,
1802                                      gp_Ax2& thePlane)
1803 {
1804   if (theAnnotationPlane.IsNull())
1805     return Standard_False;
1806   Handle(StepRepr_RepresentationItem) aPlaneItem = theAnnotationPlane->Item();
1807   if (aPlaneItem.IsNull())
1808     return Standard_False;
1809   Handle(StepGeom_Axis2Placement3d) aA2P3D;
1810   //retrieve axes from AnnotationPlane
1811   if (aPlaneItem->IsKind(STANDARD_TYPE(StepGeom_Plane))) {
1812     Handle(StepGeom_Plane) aPlane = Handle(StepGeom_Plane)::DownCast(aPlaneItem);
1813     aA2P3D = aPlane->Position();
1814   }
1815   else if (aPlaneItem->IsKind(STANDARD_TYPE(StepVisual_PlanarBox))) {
1816     Handle(StepVisual_PlanarBox) aBox = Handle(StepVisual_PlanarBox)::DownCast(aPlaneItem);
1817     aA2P3D = aBox->Placement().Axis2Placement3d();
1818   }
1819   if (aA2P3D.IsNull())
1820     return Standard_False;
1821
1822   Handle(Geom_Axis2Placement) anAxis = StepToGeom::MakeAxis2Placement(aA2P3D);
1823   thePlane = anAxis->Ax2();
1824   return Standard_True;
1825 }
1826
1827 //=======================================================================
1828 //function : readAnnotation
1829 //purpose  : read annotation plane and position for given GDT
1830 // (Dimension, Geometric_Tolerance, Datum_Feature or Placed_Datum_Target_Feature)
1831 //=======================================================================
1832 void readAnnotation(const Handle(XSControl_TransferReader)& theTR, 
1833   const Handle(Standard_Transient)& theGDT,
1834   const Handle(Standard_Transient)& theDimObject)
1835 {
1836   if (theGDT.IsNull() || theDimObject.IsNull())
1837     return;
1838   Handle(TCollection_HAsciiString) aPresentName;
1839   TopoDS_Compound aResAnnotation;
1840   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1841   const Interface_Graph& aGraph = aTP->Graph();
1842   // find the proper DraughtingModelItemAssociation
1843   Interface_EntityIterator subs = aGraph.Sharings(theGDT);
1844   Handle(StepAP242_DraughtingModelItemAssociation) aDMIA;
1845   for (subs.Start(); subs.More() && aDMIA.IsNull(); subs.Next()) {
1846     if (!subs.Value()->IsKind(STANDARD_TYPE(StepAP242_DraughtingModelItemAssociation)))
1847       continue;
1848     aDMIA = Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(subs.Value());
1849     Handle(TCollection_HAsciiString) aName = aDMIA->Name();
1850     aName->LowerCase();
1851     if (!aName->Search(new TCollection_HAsciiString("pmi representation to presentation link"))) {
1852       aDMIA = NULL;
1853     }
1854   }
1855   if (aDMIA.IsNull() || aDMIA->NbIdentifiedItem() == 0)
1856     return;
1857
1858   // calculate units
1859   Handle(StepVisual_DraughtingModel) aDModel = 
1860     Handle(StepVisual_DraughtingModel)::DownCast(aDMIA->UsedRepresentation());
1861   XSAlgo::AlgoContainer()->PrepareForTransfer();
1862   STEPControl_ActorRead anActor;
1863   anActor.PrepareUnits(aDModel, aTP);
1864   Standard_Real aFact = UnitsMethods::LengthFactor();
1865
1866   // retrieve AnnotationPlane
1867   Handle(StepRepr_RepresentationItem) aDMIAE = aDMIA->IdentifiedItemValue(1);
1868   if (aDMIAE.IsNull())
1869     return;
1870   gp_Ax2 aPlaneAxes;
1871   subs = aGraph.Sharings(aDMIAE);
1872   Handle(StepVisual_AnnotationPlane) anAnPlane;
1873   for (subs.Start(); subs.More() && anAnPlane.IsNull(); subs.Next()) {
1874     anAnPlane = Handle(StepVisual_AnnotationPlane)::DownCast(subs.Value());
1875   }
1876   Standard_Boolean isHasPlane = readAnnotationPlane(anAnPlane, aPlaneAxes);
1877
1878   // set plane axes to XCAF
1879   if (isHasPlane) {
1880     if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1881       Handle(XCAFDimTolObjects_DimensionObject) anObj = 
1882         Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1883       Handle(TColgp_HArray1OfPnt) aPnts = new TColgp_HArray1OfPnt(1, 1);
1884       anObj->SetPlane(aPlaneAxes);
1885     }
1886     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1887       Handle(XCAFDimTolObjects_DatumObject) anObj =
1888         Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1889       anObj->SetPlane(aPlaneAxes);
1890     }
1891     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1892       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1893         Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1894       anObj->SetPlane(aPlaneAxes);
1895     }
1896   }
1897
1898   // Retrieve presentation
1899   Bnd_Box aBox;
1900   if (!readPMIPresentation(aDMIAE, theTR, aFact, aResAnnotation, aPresentName, aBox))
1901     return;
1902   gp_Pnt aPtext(0., 0., 0.);
1903   // if Annotation plane location inside bounding box set it to text position
1904   // else set the center of bounding box to text position
1905   if (!aBox.IsVoid())
1906   {
1907     Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
1908     aBox.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
1909     if (isHasPlane && !aBox.IsOut(aPlaneAxes.Location())) {
1910       aPtext = aPlaneAxes.Location();
1911     }
1912     else {
1913       aPtext = gp_Pnt((aXmin + aXmax) * 0.5, (aYmin + aYmax) * 0.5, (aZmin + aZmax) * 0.5);
1914     }
1915   }
1916   else {
1917     aPtext = aPlaneAxes.Location();
1918   }
1919
1920   // set point to XCAF
1921   if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1922     Handle(XCAFDimTolObjects_DimensionObject) anObj = 
1923       Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1924     anObj->SetPointTextAttach(aPtext);
1925     anObj->SetPresentation(aResAnnotation, aPresentName);
1926   }
1927   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1928     Handle(XCAFDimTolObjects_DatumObject) anObj =
1929       Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1930       anObj->SetPointTextAttach(aPtext);
1931       anObj->SetPresentation(aResAnnotation, aPresentName);
1932   }
1933   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1934     Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1935       Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1936     anObj->SetPointTextAttach(aPtext);
1937     anObj->SetPresentation(aResAnnotation, aPresentName);
1938   }
1939   return;
1940 }
1941
1942 //=======================================================================
1943 //function : readConnectionPoints
1944 //purpose  : read connection points for given dimension
1945 //=======================================================================
1946 void readConnectionPoints(const Handle(XSControl_TransferReader)& theTR, 
1947   const Handle(Standard_Transient) theGDT,
1948   const Handle(XCAFDimTolObjects_DimensionObject)& theDimObject)
1949 {
1950   if (theGDT.IsNull() || theDimObject.IsNull())
1951     return;
1952   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1953   const Interface_Graph& aGraph = aTP->Graph();
1954
1955   //calculate units
1956   Handle(StepShape_ShapeDimensionRepresentation) aSDR = NULL;
1957   for (Interface_EntityIterator anIt = aGraph.Sharings(theGDT); aSDR.IsNull() && anIt.More(); anIt.Next()) {
1958     aSDR = Handle(StepShape_ShapeDimensionRepresentation)::DownCast(anIt.Value());
1959   }
1960   XSAlgo::AlgoContainer()->PrepareForTransfer();
1961   STEPControl_ActorRead anActor;
1962   anActor.PrepareUnits(aSDR, aTP);
1963   Standard_Real aFact = UnitsMethods::LengthFactor();
1964
1965   if (theGDT->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
1966     // retrieve derived geometry
1967     Handle(StepShape_DimensionalSize) aDim = Handle(StepShape_DimensionalSize)::DownCast(theGDT);
1968     Handle(StepRepr_DerivedShapeAspect) aDSA = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->AppliesTo());
1969     if (aDSA.IsNull())
1970       return;
1971     Handle(StepAP242_GeometricItemSpecificUsage) aGISU = NULL;
1972     for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA); aGISU.IsNull() && anIt.More(); anIt.Next()) {
1973       aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
1974     }
1975     if (aGISU.IsNull() || aGISU->NbIdentifiedItem() == 0)
1976       return;
1977     Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU->IdentifiedItem()->Value(1));
1978     if (aPoint.IsNull()) {
1979       // try Axis2Placement3d.location instead of CartesianPoint
1980       Handle(StepGeom_Axis2Placement3d) anA2P3D =
1981         Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU->IdentifiedItem()->Value(1));
1982       if (anA2P3D.IsNull())
1983         return;
1984       aPoint = anA2P3D->Location();
1985     }
1986   
1987     // set connection point to object
1988     gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
1989     theDimObject->SetPoint(aPnt);
1990   }
1991   else if (theGDT->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
1992     // retrieve derived geometry
1993     Handle(StepShape_DimensionalLocation) aDim = Handle(StepShape_DimensionalLocation)::DownCast(theGDT);
1994     Handle(StepRepr_DerivedShapeAspect) aDSA1 = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->RelatingShapeAspect());
1995     Handle(StepRepr_DerivedShapeAspect) aDSA2 = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->RelatedShapeAspect());
1996     if (aDSA1.IsNull() && aDSA2.IsNull())
1997       return;
1998     Handle(StepAP242_GeometricItemSpecificUsage) aGISU1 = NULL;
1999     Handle(StepAP242_GeometricItemSpecificUsage) aGISU2 = NULL;
2000     if (!aDSA1.IsNull()) {
2001       for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA1); aGISU1.IsNull() && anIt.More(); anIt.Next()) {
2002         aGISU1 = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2003       }
2004     }
2005     if (!aDSA2.IsNull()) {
2006       for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA2); aGISU2.IsNull() && anIt.More(); anIt.Next()) {
2007         aGISU2 = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2008       }
2009     }
2010     // first point
2011     if (!aGISU1.IsNull() && aGISU1->NbIdentifiedItem() > 0) {
2012       Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU1->IdentifiedItem()->Value(1));
2013       if (aPoint.IsNull()) {
2014         // try Axis2Placement3d.location instead of CartesianPoint
2015         Handle(StepGeom_Axis2Placement3d) anA2P3D =
2016           Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU1->IdentifiedItem()->Value(1));
2017         if (!anA2P3D.IsNull())
2018           aPoint = anA2P3D->Location();
2019       }
2020       if (!aPoint.IsNull()) {
2021         // set connection point to object
2022         gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2023         theDimObject->SetPoint(aPnt);
2024       }
2025     }
2026     // second point
2027     if (!aGISU2.IsNull() && aGISU2->NbIdentifiedItem() > 0) {
2028       Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU2->IdentifiedItem()->Value(1));
2029       if (aPoint.IsNull()) {
2030         // try Axis2Placement3d.location instead of CartesianPoint
2031         Handle(StepGeom_Axis2Placement3d) anA2P3D =
2032           Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU2->IdentifiedItem()->Value(1));
2033         if (!anA2P3D.IsNull())
2034           aPoint = anA2P3D->Location();
2035       }
2036       if (!aPoint.IsNull()) {
2037         // set connection point to object
2038         gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2039         theDimObject->SetPoint2(aPnt);
2040       }
2041     }
2042   }
2043 }
2044
2045 //=======================================================================
2046 //function : ReadDatums
2047 //purpose  : auxilary
2048 //=======================================================================
2049 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
2050                                    const Handle(XCAFDoc_DimTolTool) &DGTTool,
2051                                    const Interface_Graph &graph,
2052                                    const Handle(Transfer_TransientProcess) &TP,
2053                                    const TDF_Label TolerL,
2054                                    const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
2055 {
2056   if(GTWDR.IsNull()) return Standard_False;
2057   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
2058   if(HADR.IsNull()) return Standard_False;
2059   for(Standard_Integer idr=1; idr<=HADR->Length(); idr++) {
2060     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
2061     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
2062     if(aDatum.IsNull()) continue;
2063     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
2064     for(subs4.Start(); subs4.More(); subs4.Next()) {
2065       Handle(StepRepr_ShapeAspectRelationship) SAR = 
2066         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
2067       if(SAR.IsNull()) continue;
2068       Handle(StepDimTol_DatumFeature) DF = 
2069         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
2070       if(DF.IsNull()) continue;
2071       Interface_EntityIterator subs5 = graph.Sharings(DF);
2072       Handle(StepRepr_PropertyDefinition) PropDef;
2073       for(subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
2074         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
2075       }
2076       if(PropDef.IsNull()) continue;
2077       Handle(StepShape_AdvancedFace) AF;
2078       subs5 = graph.Sharings(PropDef);
2079       for(subs5.Start(); subs5.More(); subs5.Next()) {
2080         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2081           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
2082         if(!SDR.IsNull()) {
2083           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2084           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2085             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
2086             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2087           }
2088         }
2089       }
2090       if(AF.IsNull()) return Standard_False;
2091       Standard_Integer index = TP->MapIndex(AF);
2092       TopoDS_Shape aSh;
2093       if(index >0) {
2094         Handle(Transfer_Binder) binder = TP->MapItem(index);
2095         aSh = TransferBRep::ShapeResult(binder);
2096       }
2097       if(aSh.IsNull()) continue; 
2098       TDF_Label shL;
2099       if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2100       DGTTool->SetDatum(shL,TolerL,PropDef->Name(),PropDef->Description(),aDatum->Identification());
2101     }
2102   }
2103   return Standard_True;
2104 }
2105
2106 //=======================================================================
2107 //function : FindShapeIndexForDGT
2108 //purpose  : auxiliary find shape index in map og imported shapes
2109 //=======================================================================
2110 static Standard_Integer FindShapeIndexForDGT(const Handle(Standard_Transient)& theEnt,
2111   const Handle(XSControl_WorkSession)& theWS)
2112 {
2113   const Handle(Transfer_TransientProcess) &aTP = theWS->TransferReader()->TransientProcess();
2114   // try to find index of given entity
2115   Standard_Integer anIndex = aTP->MapIndex(theEnt);
2116   if (anIndex > 0)
2117     return anIndex;
2118   // if theEnt is a geometry item try to find its topological item
2119   const Interface_Graph& aGraph = aTP->Graph();
2120   Interface_EntityIterator anIter = aGraph.Sharings(theEnt);
2121   for (anIter.Start(); anIter.More(); anIter.Next()) {
2122     if (anIter.Value()->IsKind(STANDARD_TYPE(StepShape_TopologicalRepresentationItem)))
2123     {
2124       anIndex = aTP->MapIndex(anIter.Value());
2125       if (anIndex > 0)
2126         return anIndex;
2127     }
2128   }
2129   return 0;
2130 }
2131
2132 //=======================================================================
2133 //function : collectShapeAspect
2134 //purpose  : 
2135 //=======================================================================
2136 static void collectShapeAspect(const Handle(StepRepr_ShapeAspect)& theSA,
2137                                const Handle(XSControl_WorkSession)& theWS,
2138                                NCollection_Sequence<Handle(StepRepr_ShapeAspect)>& theSAs)
2139 {
2140   if (theSA.IsNull())
2141     return;
2142   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2143   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2144   const Interface_Graph& aGraph = aTP->Graph();
2145   // Retrieve Shape_Aspect, connected to Representation_Item from Derived_Shape_Aspect
2146   if (theSA->IsKind(STANDARD_TYPE(StepRepr_DerivedShapeAspect))) {
2147     Interface_EntityIterator anIter = aGraph.Sharings(theSA);
2148     Handle(StepRepr_ShapeAspectDerivingRelationship) aSADR = NULL;
2149     for (; aSADR.IsNull() && anIter.More(); anIter.Next()) {
2150       aSADR = Handle(StepRepr_ShapeAspectDerivingRelationship)::DownCast(anIter.Value());
2151     }
2152     if (!aSADR.IsNull())
2153       collectShapeAspect(aSADR->RelatedShapeAspect(), theWS, theSAs);
2154   }
2155   else if (theSA->IsKind(STANDARD_TYPE(StepDimTol_DatumFeature)) ||
2156     theSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget))) {
2157     theSAs.Append(theSA);
2158     return;
2159   }
2160   else {
2161     // Find all children Shape_Aspect
2162     Standard_Boolean isSimple = Standard_True;
2163     Interface_EntityIterator anIter = aGraph.Sharings(theSA);
2164     for (; anIter.More(); anIter.Next()) {
2165       if (anIter.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship)) &&
2166           !anIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2167         Handle(StepRepr_ShapeAspectRelationship) aSAR =
2168           Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIter.Value());
2169         if (aSAR->RelatingShapeAspect() == theSA && !aSAR->RelatedShapeAspect().IsNull()
2170             && !aSAR->RelatedShapeAspect()->IsKind(STANDARD_TYPE(StepDimTol_Datum))) {
2171           collectShapeAspect(aSAR->RelatedShapeAspect(), theWS, theSAs);
2172           isSimple = Standard_False;
2173         }
2174       }
2175     }
2176     // If not Composite_Shape_Aspect (or subtype) append to sequence.
2177     if (isSimple)
2178       theSAs.Append(theSA);
2179   }
2180 }
2181
2182 //=======================================================================
2183 //function : getShapeLabel
2184 //purpose  : 
2185 //=======================================================================
2186
2187 static TDF_Label getShapeLabel(const Handle(StepRepr_RepresentationItem)& theItem,
2188                                const Handle(XSControl_WorkSession)& theWS,
2189                                const Handle(XCAFDoc_ShapeTool)& theShapeTool)
2190 {
2191   TDF_Label aShapeL;
2192   const Handle(Transfer_TransientProcess) &aTP = theWS->TransferReader()->TransientProcess();
2193   Standard_Integer index = FindShapeIndexForDGT(theItem, theWS);
2194   TopoDS_Shape aShape;
2195   if (index > 0) {
2196     Handle(Transfer_Binder) aBinder = aTP->MapItem(index);
2197     aShape = TransferBRep::ShapeResult(aBinder);
2198   }
2199   if (aShape.IsNull())
2200     return aShapeL;
2201   theShapeTool->Search(aShape, aShapeL, Standard_True, Standard_True, Standard_True);
2202   return aShapeL;
2203 }
2204
2205 //=======================================================================
2206 //function : setDatumToXCAF
2207 //purpose  : 
2208 //=======================================================================
2209
2210 Standard_Boolean STEPCAFControl_Reader::setDatumToXCAF(const Handle(StepDimTol_Datum)& theDat,
2211                                                        const TDF_Label theGDTL,
2212                                                        const Standard_Integer thePositionCounter,
2213                                                        const XCAFDimTolObjects_DatumModifiersSequence& theXCAFModifiers,
2214                                                        const XCAFDimTolObjects_DatumModifWithValue theXCAFModifWithVal,
2215                                                        const Standard_Real theModifValue,
2216                                                        const Handle(TDocStd_Document)& theDoc,
2217                                                        const Handle(XSControl_WorkSession)& theWS)
2218 {
2219   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
2220   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
2221   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2222   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2223   const Interface_Graph& aGraph = aTP->Graph();
2224   Handle(XCAFDoc_Datum) aDat;
2225   TDF_LabelSequence aShapeLabels;
2226   Handle(XCAFDimTolObjects_DatumObject) aDatObj = new XCAFDimTolObjects_DatumObject();
2227
2228   // Collect all links to shapes
2229   NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2230   Interface_EntityIterator anIterD = aGraph.Sharings(theDat);
2231   for (anIterD.Start(); anIterD.More(); anIterD.Next()) {
2232     Handle(StepRepr_ShapeAspectRelationship) aSAR = Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterD.Value());
2233     if (aSAR.IsNull() || aSAR->RelatingShapeAspect().IsNull())
2234       continue;
2235     collectShapeAspect(aSAR->RelatingShapeAspect(), theWS, aSAs);
2236     Handle(StepDimTol_DatumFeature) aDF = Handle(StepDimTol_DatumFeature)::DownCast(aSAR->RelatingShapeAspect());
2237     if (!aSAR->RelatingShapeAspect()->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)))
2238       readAnnotation(aTR, aSAR->RelatingShapeAspect(), aDatObj);
2239   }
2240
2241   // Collect shape labels
2242   for (Standard_Integer i = 1; i <= aSAs.Length(); i++) {
2243     Handle(StepRepr_ShapeAspect) aSA = aSAs.Value(i);
2244     if (aSA.IsNull())
2245       continue;
2246     // Skip datum targets
2247     if (aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)))
2248       continue;
2249
2250     // Process all connected GISU
2251     Interface_EntityIterator anIter = aGraph.Sharings(aSA);
2252     for (; anIter.More(); anIter.Next()) {
2253       Handle(StepAP242_GeometricItemSpecificUsage) aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIter.Value());
2254       if (aGISU.IsNull())
2255         continue;
2256       for (Standard_Integer j = 1; j <= aGISU->NbIdentifiedItem(); j++) {
2257         TDF_Label aShapeL = getShapeLabel(aGISU->IdentifiedItemValue(j), theWS, aSTool);
2258         if (!aShapeL.IsNull())
2259           aShapeLabels.Append(aShapeL);
2260       }
2261     }
2262   }
2263
2264   // Process datum targets and create objects for them
2265   Standard_Boolean isExistDatumTarget = Standard_False;
2266   for (Standard_Integer i = 1; i <= aSAs.Length(); i++) {
2267     Handle(StepDimTol_PlacedDatumTargetFeature) aDT = Handle(StepDimTol_PlacedDatumTargetFeature)::DownCast(aSAs.Value(i));
2268     if (aDT.IsNull())
2269       continue;
2270     Handle(XCAFDimTolObjects_DatumObject) aDatTargetObj = new XCAFDimTolObjects_DatumObject();
2271     XCAFDimTolObjects_DatumTargetType aType;
2272     if (!STEPCAFControl_GDTProperty::GetDatumTargetType(aDT->Description(), aType))
2273       continue;
2274     aDatTargetObj->SetDatumTargetType(aType);
2275     Standard_Boolean isValidDT = Standard_False;
2276
2277     // Feature for datum target
2278     TDF_LabelSequence aDTShapeLabels;
2279     Interface_EntityIterator aDTIter = aGraph.Sharings(aDT);
2280     Handle(StepRepr_FeatureForDatumTargetRelationship) aRelationship;
2281     for (; aDTIter.More() && aRelationship.IsNull(); aDTIter.Next()) {
2282       aRelationship = Handle(StepRepr_FeatureForDatumTargetRelationship)::DownCast(aDTIter.Value());
2283     }
2284     if (!aRelationship.IsNull()) {
2285       Handle(StepRepr_ShapeAspect) aSA = aRelationship->RelatingShapeAspect();
2286       Interface_EntityIterator aSAIter = aGraph.Sharings(aSA);
2287       for (; aSAIter.More(); aSAIter.Next()) {
2288         Handle(StepAP242_GeometricItemSpecificUsage) aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(aSAIter.Value());
2289         if (aGISU.IsNull())
2290           continue;
2291         for (Standard_Integer j = 1; j <= aGISU->NbIdentifiedItem(); j++) {
2292           TDF_Label aShapeL = getShapeLabel(aGISU->IdentifiedItemValue(j), theWS, aSTool);
2293           if (!aShapeL.IsNull()) {
2294             aDTShapeLabels.Append(aShapeL);
2295             isValidDT = Standard_True;
2296           }
2297         }
2298       }
2299     }
2300
2301     if (aType != XCAFDimTolObjects_DatumTargetType_Area && !isValidDT) {
2302       // Try another way of feature connection
2303       for (aDTIter.Start(); aDTIter.More(); aDTIter.Next()) {
2304         Handle(StepAP242_GeometricItemSpecificUsage) aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(aDTIter.Value());
2305         if (aGISU.IsNull())
2306           continue;
2307         for (Standard_Integer j = 1; j <= aGISU->NbIdentifiedItem(); j++) {
2308           TDF_Label aShapeL = getShapeLabel(aGISU->IdentifiedItemValue(j), theWS, aSTool);
2309           if (!aShapeL.IsNull()) {
2310             aDTShapeLabels.Append(aShapeL);
2311             isValidDT = Standard_True;
2312           }
2313         }
2314       }
2315     }
2316
2317     if (aType == XCAFDimTolObjects_DatumTargetType_Area) {
2318       // Area datum target
2319       Interface_EntityIterator anIterDTF = aGraph.Shareds(aDT);
2320       Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2321       for (; anIterDTF.More() && aGISU.IsNull(); anIterDTF.Next()) {
2322         aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDTF.Value());
2323       }
2324       Handle(StepRepr_RepresentationItem) anItem;
2325       if (aGISU->NbIdentifiedItem() > 0)
2326         anItem = aGISU->IdentifiedItemValue(1);
2327       if (anItem.IsNull())
2328         continue;
2329       Standard_Integer anItemIndex = FindShapeIndexForDGT(anItem, theWS);
2330       if (anItemIndex > 0) {
2331         Handle(Transfer_Binder) aBinder = aTP->MapItem(anItemIndex);
2332         TopoDS_Shape anItemShape = TransferBRep::ShapeResult(aBinder);
2333         aDatTargetObj->SetDatumTarget(anItemShape);
2334         isValidDT = Standard_True;
2335       }
2336     }
2337     else {
2338       // Point/line/rectangle/circle datum targets 
2339       Interface_EntityIterator anIter = aGraph.Sharings(aDT);
2340       Handle(StepRepr_PropertyDefinition) aPD;
2341       for (; anIter.More() && aPD.IsNull(); anIter.Next()) {
2342         aPD = Handle(StepRepr_PropertyDefinition)::DownCast(anIter.Value());
2343       }
2344       if (!aPD.IsNull()) {
2345         anIter = aGraph.Sharings(aPD);
2346         Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
2347         for (; anIter.More() && aSDR.IsNull(); anIter.Next()) {
2348           aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(anIter.Value());
2349         }
2350         if (!aSDR.IsNull()) {
2351           Handle(StepShape_ShapeRepresentationWithParameters) aSRWP
2352             = Handle(StepShape_ShapeRepresentationWithParameters)::DownCast(aSDR->UsedRepresentation());
2353           if (!aSRWP.IsNull()) {
2354             isValidDT = Standard_True;
2355             // Collect parameters of datum target
2356             for (Standard_Integer j = aSRWP->Items()->Lower(); j <= aSRWP->Items()->Upper(); j++)
2357             {
2358               if (aSRWP->ItemsValue(j).IsNull())
2359                 continue;
2360               if (aSRWP->ItemsValue(j)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2361               {
2362                 Handle(StepGeom_Axis2Placement3d) anAx
2363                   = Handle(StepGeom_Axis2Placement3d)::DownCast(aSRWP->ItemsValue(j));
2364                 XSAlgo::AlgoContainer()->PrepareForTransfer();
2365                 STEPControl_ActorRead anActor;
2366                 anActor.PrepareUnits(aSRWP, aTP);
2367                 Handle(Geom_Axis2Placement) anAxis = StepToGeom::MakeAxis2Placement(anAx);
2368                 aDatTargetObj->SetDatumTargetAxis(anAxis->Ax2());
2369               }
2370               else if (aSRWP->ItemsValue(j)->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit)))
2371               {
2372                 Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aM =
2373                   Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aSRWP->ItemsValue(j));
2374                 Standard_Real aVal = aM->GetMeasureWithUnit()->ValueComponent();
2375                 StepBasic_Unit anUnit = aM->GetMeasureWithUnit()->UnitComponent();
2376                 if (anUnit.IsNull())
2377                   continue;
2378                 Handle(StepBasic_NamedUnit) aNU = anUnit.NamedUnit();
2379                 if (aNU.IsNull())
2380                   continue;
2381                 STEPConstruct_UnitContext anUnitCtx;
2382                 anUnitCtx.ComputeFactors(aNU);
2383                 aVal = aVal * anUnitCtx.LengthFactor();
2384                 if (aM->Name()->String().IsEqual("target length") ||
2385                   aM->Name()->String().IsEqual("target diameter"))
2386                   aDatTargetObj->SetDatumTargetLength(aVal);
2387                 else
2388                   aDatTargetObj->SetDatumTargetWidth(aVal);
2389               }
2390             }
2391           }
2392         }
2393       }
2394     }
2395
2396     // Create datum target object
2397     if (isValidDT) {
2398       TDF_Label aDatL = aDGTTool->AddDatum();
2399       myGDTMap.Bind(aDT, aDatL);
2400       aDGTTool->Lock(aDatL);
2401       aDat = XCAFDoc_Datum::Set(aDatL);
2402       aDGTTool->SetDatum(aDTShapeLabels, aDatL);
2403       aDatTargetObj->SetName(theDat->Identification());
2404       aDatTargetObj->SetPosition(thePositionCounter);
2405       if (!theXCAFModifiers.IsEmpty())
2406         aDatTargetObj->SetModifiers(theXCAFModifiers);
2407       if (theXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None)
2408         aDatTargetObj->SetModifierWithValue(theXCAFModifWithVal, theModifValue);
2409       aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2410       aDatTargetObj->IsDatumTarget(Standard_True);
2411       aDatTargetObj->SetDatumTargetNumber(aDT->TargetId()->IntegerValue());
2412       readAnnotation(aTR, aDT, aDatTargetObj);
2413       aDat->SetObject(aDatTargetObj);
2414       isExistDatumTarget = Standard_True;
2415     }
2416   }
2417
2418   if (aShapeLabels.Length() > 0 || !isExistDatumTarget) {
2419     // Create object for datum
2420     TDF_Label aDatL = aDGTTool->AddDatum();
2421     myGDTMap.Bind(theDat, aDatL);
2422     // bind datum label with all reference datum_feature entities
2423     for (Standard_Integer i = 1; i <= aSAs.Length(); i++) {
2424       Handle(StepRepr_ShapeAspect) aSA = aSAs.Value(i);
2425       if (aSA.IsNull() || aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)))
2426         continue;
2427       myGDTMap.Bind(aSA, aDatL);
2428     }
2429     aDGTTool->Lock(aDatL);
2430     aDat = XCAFDoc_Datum::Set(aDatL);
2431     aDGTTool->SetDatum(aShapeLabels, aDatL);
2432     aDatObj->SetName(theDat->Identification());
2433     aDatObj->SetPosition(thePositionCounter);
2434     if (!theXCAFModifiers.IsEmpty())
2435       aDatObj->SetModifiers(theXCAFModifiers);
2436     if (theXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None)
2437       aDatObj->SetModifierWithValue(theXCAFModifWithVal, theModifValue);
2438     aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2439     if (aDatObj->GetPresentation().IsNull()) {
2440       // Try find annotation connected to datum entity (not right case, according recommended practices)
2441       readAnnotation(aTR, theDat, aDatObj);
2442     }
2443     aDat->SetObject(aDatObj);
2444   }
2445
2446   return Standard_True;
2447 }
2448
2449
2450 //=======================================================================
2451 //function : ReadDatums
2452 //purpose  : auxilary
2453 //=======================================================================
2454 Standard_Boolean STEPCAFControl_Reader::readDatumsAP242(const Handle(Standard_Transient)& theEnt,
2455                                                         const TDF_Label theGDTL,
2456                                                         const Handle(TDocStd_Document)& theDoc,
2457                                                         const Handle(XSControl_WorkSession)& theWS)
2458 {
2459   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2460   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2461   const Interface_Graph& aGraph = aTP->Graph();
2462
2463   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2464   for(anIter.Start(); anIter.More(); anIter.Next()) {
2465     Handle(Standard_Transient) anAtr = anIter.Value();
2466     if(anAtr->IsKind(STANDARD_TYPE(StepDimTol_DatumSystem)))
2467     {
2468       Standard_Integer aPositionCounter = 0;//position on frame 
2469       Handle(StepDimTol_DatumSystem) aDS = Handle(StepDimTol_DatumSystem)::DownCast(anAtr);
2470       Interface_EntityIterator anIterDS = aGraph.Sharings(aDS);
2471       for(anIterDS.Start(); anIterDS.More(); anIterDS.Next()) {
2472         Handle(Standard_Transient) anAtrDS = anIterDS.Value();
2473         if(anAtrDS->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2474         {
2475           //get axis
2476           Handle(StepAP242_GeometricItemSpecificUsage)aAxGISUI
2477             = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anAtrDS);
2478           if (aAxGISUI->IdentifiedItemValue(1)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2479           {
2480             Handle(StepGeom_Axis2Placement3d) anAx
2481               = Handle(StepGeom_Axis2Placement3d)::DownCast(aAxGISUI->IdentifiedItemValue(1));
2482             Handle(XCAFDoc_GeomTolerance) aTol;
2483             if(theGDTL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aTol))
2484             {
2485               Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aTol->GetObject();
2486               Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2487               Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2488               Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2489               gp_Dir aDir;
2490               gp_Dir aDirR;
2491               gp_Pnt aPnt;
2492               if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2493                 !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2494                 !aLocArr.IsNull() && aLocArr->Length() > 2)
2495               {
2496                 aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2497                 aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2498                 aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2499                 gp_Ax2 anA(aPnt, aDir, aDirR);
2500                 anObj->SetAxis(anA);
2501                 aTol->SetObject(anObj);
2502               }
2503             }
2504           }
2505         }
2506       }
2507       if (aDS->NbConstituents() > 0)
2508       {
2509         //get datum feature and datum target from datum system
2510         Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aDRCA = aDS->Constituents();
2511         if(!aDRCA.IsNull())
2512         {
2513           for(Standard_Integer i = aDRCA->Lower(); i <= aDRCA->Upper(); i++)
2514           {
2515             Handle(StepDimTol_DatumReferenceCompartment) aDRC = aDRCA->Value(i);
2516             //gete modifiers
2517             Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModif = aDRC->Modifiers();
2518             XCAFDimTolObjects_DatumModifiersSequence aXCAFModifiers;
2519             XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal = XCAFDimTolObjects_DatumModifWithValue_None;
2520             Standard_Real aModifValue = 0;
2521             if(!aModif.IsNull())
2522             {
2523               for(Standard_Integer m = aModif->Lower(); m <= aModif->Upper(); m++)
2524               {
2525                 if(aModif->Value(m).CaseNumber() == 2)
2526                   aXCAFModifiers.Append(
2527                   (XCAFDimTolObjects_DatumSingleModif)aModif->Value(m).
2528                   SimpleDatumReferenceModifierMember()->Value());
2529                 else if (aModif->Value(m).CaseNumber() == 1)
2530                 {
2531                   aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModif->Value(m).DatumReferenceModifierWithValue()->ModifierType() + 1);
2532                   Standard_Real aVal = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2533                   StepBasic_Unit anUnit = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2534                   if(anUnit.IsNull()) continue;
2535                   if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2536                   Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2537                   STEPConstruct_UnitContext anUnitCtx;
2538                   anUnitCtx.ComputeFactors(NU);
2539                   aModifValue = aVal * anUnitCtx.LengthFactor();
2540                 }
2541               }
2542             }
2543             aPositionCounter++;
2544             Interface_EntityIterator anIterDRC = aGraph.Shareds(aDRC);
2545             for(anIterDRC.Start(); anIterDRC.More(); anIterDRC.Next()) {
2546               
2547               if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2548               {
2549                 Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRC.Value());
2550                 setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2551               }
2552               else if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_DatumReferenceElement)))
2553               {
2554                 Handle(StepDimTol_DatumReferenceElement) aDRE 
2555                   = Handle(StepDimTol_DatumReferenceElement)::DownCast(anIterDRC.Value());
2556                 //get modifiers from group of datums
2557                 Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifE = aDRE->Modifiers();
2558                 if(!aModifE.IsNull())
2559                 {
2560                   for(Standard_Integer k = aModifE->Lower(); k <= aModifE->Upper(); k++)
2561                   {
2562                     if(aModifE->Value(k).CaseNumber() == 2)
2563                       aXCAFModifiers.Append(
2564                       (XCAFDimTolObjects_DatumSingleModif)aModifE->Value(k).
2565                       SimpleDatumReferenceModifierMember()->Value());
2566                     else if (aModifE->Value(k).CaseNumber() == 1)
2567                     {
2568                       aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierType() + 1);
2569                       Standard_Real aVal = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2570                       StepBasic_Unit anUnit = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2571                       if(anUnit.IsNull()) continue;
2572                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2573                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2574                       STEPConstruct_UnitContext anUnitCtx;
2575                       anUnitCtx.ComputeFactors(NU);
2576                       aModifValue = aVal * anUnitCtx.LengthFactor();
2577                     }
2578                   }
2579                 }
2580                 Interface_EntityIterator anIterDRE = aGraph.Shareds(aDRE);
2581                 for(anIterDRE.Start(); anIterDRE.More(); anIterDRE.Next()) {
2582                   if(anIterDRE.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2583                   {
2584                     Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRE.Value());
2585                     setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2586                   }
2587                 }
2588               }
2589             }
2590           }
2591         }
2592       }
2593     }
2594   }
2595   return Standard_True;
2596 }
2597
2598 //=======================================================================
2599 //function : createGeomTolObjectInXCAF
2600 //purpose  : 
2601 //=======================================================================
2602 TDF_Label STEPCAFControl_Reader::createGDTObjectInXCAF(const Handle(Standard_Transient)& theEnt,
2603                                                        const Handle(TDocStd_Document)& theDoc,
2604                                                        const Handle(XSControl_WorkSession)& theWS)
2605 {
2606   TDF_Label aGDTL;
2607   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2608      !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) && 
2609      !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2610   {
2611     return aGDTL;
2612   }
2613
2614   Handle(TCollection_HAsciiString) aSemanticName;
2615
2616   // protection against invalid input
2617   if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2618     Handle(StepDimTol_GeometricTolerance) aGeomTol = Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2619     if (aGeomTol->TolerancedShapeAspect().IsNull())
2620       return aGDTL;
2621     aSemanticName = aGeomTol->Name();
2622   }
2623   if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2624     Handle(StepShape_DimensionalSize) aDim = Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2625     if (aDim->AppliesTo().IsNull())
2626       return aGDTL;
2627     aSemanticName = aDim->Name();
2628   }
2629   if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2630     Handle(StepShape_DimensionalLocation) aDim = Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
2631     if (aDim->RelatedShapeAspect().IsNull() || aDim->RelatingShapeAspect().IsNull())
2632       return aGDTL;
2633     aSemanticName = aDim->Name();
2634   }
2635
2636   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2637   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2638   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2639   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2640   const Interface_Graph& aGraph = aTP->Graph();
2641   Standard_Boolean isAllAround = Standard_False;
2642   Standard_Boolean isAllOver = Standard_False;
2643   
2644   // find RepresentationItem for current Ent
2645   NCollection_Sequence<Handle(Standard_Transient)> aSeqRI1, aSeqRI2;
2646
2647   // Collect all Shape_Aspect entities
2648   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2649   for(anIter.Start(); anIter.More(); anIter.Next()) {
2650     Handle(Standard_Transient) anAtr = anIter.Value();
2651     NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2652     if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)))
2653     {
2654       //if associating tolerances with part (All-Over)
2655       Interface_EntityIterator anIterSDR = aGraph.Sharings(anAtr);
2656       for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) 
2657       {
2658         Handle(Standard_Transient) anAtrSDR = anIterSDR.Value();
2659         if(anAtrSDR->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2660         {
2661           isAllOver = Standard_True;
2662           Interface_EntityIterator anIterABSR = aGraph.Shareds(anAtrSDR);
2663           for(anIterABSR.Start(); anIterABSR.More(); anIterABSR.Next()) 
2664           {
2665             Handle(Standard_Transient) anAtrABSR = anIterABSR.Value();
2666             if(anAtrABSR->IsKind(STANDARD_TYPE(StepShape_AdvancedBrepShapeRepresentation)))
2667             {
2668               aSeqRI1.Append(anAtrABSR);
2669             }
2670           }
2671         }
2672       }
2673     }
2674     else if(anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) || 
2675       anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2676     {
2677       //if tolerance attached to dimension
2678       Interface_EntityIterator anIterDim = aGraph.Shareds(anAtr);
2679       for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) 
2680       {
2681         Handle(StepRepr_ShapeAspect) aSA = Handle(StepRepr_ShapeAspect)::DownCast(anIterDim.Value());
2682         if(!aSA.IsNull()) {
2683           collectShapeAspect(aSA, theWS, aSAs);
2684         }
2685       }
2686     }
2687     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2688     {
2689       if(anAtr->IsKind(STANDARD_TYPE(StepRepr_AllAroundShapeAspect)))
2690       {
2691         // if applyed AllAround Modifier
2692         isAllAround = Standard_True;
2693       }
2694       // dimensions and default tolerances
2695       Handle(StepRepr_ShapeAspect) aSA = Handle(StepRepr_ShapeAspect)::DownCast(anAtr);
2696       if(!aSA.IsNull()) {
2697         collectShapeAspect(aSA, theWS, aSAs);
2698       }
2699     }
2700
2701     // Collect all representation items
2702     if(!aSAs.IsEmpty())
2703     {
2704       //get representation items
2705       NCollection_Sequence<Handle(Standard_Transient)> aSeqRI;
2706       for(Standard_Integer i = aSAs.Lower(); i <= aSAs.Upper(); i++)
2707       {
2708         Interface_EntityIterator anIterSA = aGraph.Sharings(aSAs.Value(i));
2709         Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2710         Handle(StepRepr_PropertyDefinition) PropD;
2711         for(anIterSA.Start(); anIterSA.More() && aGISU.IsNull() && PropD.IsNull(); anIterSA.Next()) {
2712           aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2713           PropD = Handle(StepRepr_PropertyDefinition)::DownCast(anIterSA.Value());
2714         }
2715         if(!PropD.IsNull())//for old version
2716         {
2717           Handle(StepRepr_RepresentationItem) RI;
2718           Interface_EntityIterator subs4 = aGraph.Sharings(PropD);
2719           for(subs4.Start(); subs4.More(); subs4.Next()) {
2720             Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2721               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
2722             if(!SDR.IsNull()) {
2723               Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2724               if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2725                 RI = Repr->ItemsValue(1);
2726               }
2727             }
2728           }
2729           if(RI.IsNull()) continue;
2730
2731           if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2732             // read dimensions
2733             Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
2734             if(EC.IsNull()) continue;
2735             Handle(TCollection_HAsciiString) aName;
2736             Handle(StepShape_DimensionalSize) DimSize = 
2737               Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2738             Standard_Real dim1=-1.,dim2=-1.;
2739             subs4 = aGraph.Sharings(DimSize);
2740             for(subs4.Start(); subs4.More(); subs4.Next()) {
2741               Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR = 
2742                 Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
2743               if(!DimCharR.IsNull()) {
2744                 Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
2745                 if(!SDimR.IsNull() && SDimR->NbItems()>0) {
2746                   Handle(StepRepr_RepresentationItem) anItem = SDimR->ItemsValue(1);
2747                   Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(anItem);
2748                   if(!VR.IsNull()) {
2749                     aName = VR->Name();
2750                     //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
2751                     //if(CID.IsNull()) continue;
2752                     //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
2753                     //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
2754                     //if(CIDM.IsNull()) continue;
2755                     //if(CIDM->ArrTransient().IsNull()) continue;
2756                     //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
2757                     //if(CID.CaseMem(CIDM)==1)
2758                     //  HARI = CID.ListRepresentationItem();
2759                     //if(CID.CaseMem(CIDM)==2)
2760                     //  HARI = CID.SetRepresentationItem();
2761                     Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
2762                     if(HARI.IsNull()) continue;
2763                     if(HARI->Length()>0) {
2764                       Handle(StepRepr_RepresentationItem) RI1 = HARI->Value(1);
2765                       if(RI1.IsNull()) continue;
2766                       if(RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2767                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2768                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
2769                         dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2770                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2771                         if(anUnit.IsNull()) continue;
2772                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2773                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2774                         STEPConstruct_UnitContext anUnitCtx;
2775                         anUnitCtx.ComputeFactors(NU);
2776                         dim1 = dim1 * anUnitCtx.LengthFactor();
2777                       }
2778                     }
2779                     if(HARI->Length()>1) {
2780                       Handle(StepRepr_RepresentationItem) RI2 = HARI->Value(2);
2781                       if(RI2.IsNull()) continue;
2782                       if(RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2783                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2784                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
2785                         dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2786                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2787                         if(anUnit.IsNull()) continue;
2788                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2789                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2790                         STEPConstruct_UnitContext anUnitCtx;
2791                         anUnitCtx.ComputeFactors(NU);
2792                         dim2 = dim2 * anUnitCtx.LengthFactor();
2793                       }
2794                     }
2795                   }
2796                 }
2797               }
2798             }
2799             if(dim1<0) continue;
2800             if(dim2<0) dim2=dim1;
2801             //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
2802             // now we know edge_curve and value range therefore
2803             // we can create corresponding D&GT labels
2804             Standard_Integer index = aTP->MapIndex(EC);
2805             TopoDS_Shape aSh;
2806             if(index >0) {
2807               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2808               aSh = TransferBRep::ShapeResult(binder);
2809             }
2810             if(aSh.IsNull()) continue; 
2811             TDF_Label shL;
2812             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2813             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,2);
2814             arr->SetValue(1,dim1);
2815             arr->SetValue(2,dim2);
2816             aDGTTool->SetDimTol(shL,1,arr,aName,DimSize->Name());
2817           }
2818           // read tolerances and datums
2819           else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2820             Handle(StepDimTol_GeometricTolerance) GT =
2821               Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2822             // read common data for tolerance
2823             //Standard_Real dim = GT->Magnitude()->ValueComponent();
2824             Handle (StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
2825             if(dim3.IsNull()) continue;
2826             Standard_Real dim = dim3->ValueComponent();
2827             StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
2828             if(anUnit.IsNull()) continue;
2829             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2830             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2831             STEPConstruct_UnitContext anUnitCtx;
2832             anUnitCtx.ComputeFactors(NU);
2833             dim = dim * anUnitCtx.LengthFactor();
2834             //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
2835             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,1);
2836             arr->SetValue(1,dim);
2837             Handle(TCollection_HAsciiString) aName = GT->Name();
2838             Handle(TCollection_HAsciiString) aDescription = GT->Description();
2839             Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2840             if(AF.IsNull()) continue;
2841             Standard_Integer index = aTP->MapIndex(AF);
2842             TopoDS_Shape aSh;
2843             if(index >0) {
2844               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2845               aSh = TransferBRep::ShapeResult(binder);
2846             }
2847             if(aSh.IsNull()) continue; 
2848             TDF_Label shL;
2849             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2850             // read specific data for tolerance
2851             if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
2852               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2853                 Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(theEnt);
2854               Standard_Integer kind=20;
2855               Handle(StepDimTol_ModifiedGeometricTolerance) MGT = 
2856                 GTComplex->GetModifiedGeometricTolerance();
2857               if(!MGT.IsNull()) {
2858                 kind = kind + MGT->Modifier()+1;
2859               }
2860               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2861               // translate datums connected with this tolerance
2862               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2863                 GTComplex->GetGeometricToleranceWithDatumReference();
2864               if(!GTWDR.IsNull()) {
2865                 ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2866               }
2867             }
2868             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
2869               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2870                 Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(theEnt);
2871               if(GTWDR.IsNull()) continue;
2872               Standard_Integer kind = 0;
2873               if     (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
2874               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
2875               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
2876               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
2877               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
2878               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
2879               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
2880               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
2881               //cout<<"GTWDR: kind="<<kind<<endl;
2882               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2883               ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2884             }
2885             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
2886               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2887                 Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(theEnt);
2888               Standard_Integer kind = 35 + MGT->Modifier();
2889               aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2890             }
2891             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
2892               aDGTTool->SetDimTol(shL,38,arr,aName,aDescription);
2893             }
2894             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
2895               aDGTTool->SetDimTol(shL,39,arr,aName,aDescription);
2896             }
2897             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
2898               aDGTTool->SetDimTol(shL,40,arr,aName,aDescription);
2899             }
2900             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
2901               aDGTTool->SetDimTol(shL,41,arr,aName,aDescription);
2902             }
2903             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
2904               aDGTTool->SetDimTol(shL,42,arr,aName,aDescription);
2905             }
2906             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
2907               aDGTTool->SetDimTol(shL,43,arr,aName,aDescription);
2908             }
2909             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
2910               aDGTTool->SetDimTol(shL,44,arr,aName,aDescription);
2911             }
2912           }
2913         }
2914         else
2915         {
2916           if(aGISU.IsNull()) continue;
2917           Standard_Integer j =1;
2918           for ( ; j <= aGISU->NbIdentifiedItem(); j++) {
2919             aSeqRI.Append(aGISU->IdentifiedItemValue(j));
2920           }
2921         }
2922       }
2923       if(!aSeqRI.IsEmpty())
2924       {
2925         if(aSeqRI1.IsEmpty())
2926           aSeqRI1 = aSeqRI;
2927         else 
2928           aSeqRI2 = aSeqRI;
2929       }
2930     }
2931   }
2932   if(aSeqRI1.IsEmpty()) 
2933     return aGDTL;
2934
2935   TDF_LabelSequence aShLS1, aShLS2;
2936
2937   // Collect shapes
2938   for(Standard_Integer i = aSeqRI1.Lower(); i <= aSeqRI1.Upper() ;i++)
2939   {
2940     Standard_Integer anIndex = FindShapeIndexForDGT(aSeqRI1.Value(i), theWS);
2941     TopoDS_Shape aSh;
2942     if(anIndex > 0) {
2943       Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2944       aSh = TransferBRep::ShapeResult(aBinder);
2945     }
2946     if(!aSh.IsNull())
2947     {
2948       TDF_Label aShL;
2949       aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2950       if (aShL.IsNull() && aSh.ShapeType() == TopAbs_WIRE)
2951       {
2952         TopExp_Explorer ex(aSh, TopAbs_EDGE, TopAbs_SHAPE);
2953         while (ex.More())
2954         {
2955           TDF_Label edgeL;
2956           aSTool->Search(ex.Current(), edgeL, Standard_True, Standard_True, Standard_True);
2957           if (!edgeL.IsNull())
2958             aShLS1.Append(edgeL);
2959           ex.Next();
2960         }
2961       }
2962       if (!aShL.IsNull())
2963         aShLS1.Append(aShL);
2964     }
2965   }
2966   if (!aSeqRI2.IsEmpty())
2967   {
2968     //for dimensional location
2969     for(Standard_Integer i = aSeqRI2.Lower(); i <= aSeqRI2.Upper() ;i++)
2970     {
2971       Standard_Integer anIndex = FindShapeIndexForDGT(aSeqRI2.Value(i), theWS);
2972       TopoDS_Shape aSh;
2973       if(anIndex >0) {
2974         Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2975         aSh = TransferBRep::ShapeResult(aBinder);
2976       }
2977       if(!aSh.IsNull())
2978       {
2979         TDF_Label aShL;
2980         aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2981         if (aShL.IsNull() && aSh.ShapeType() == TopAbs_WIRE)
2982         {
2983           TopExp_Explorer ex(aSh, TopAbs_EDGE, TopAbs_SHAPE);
2984           while (ex.More())
2985           {
2986             TDF_Label edgeL;
2987             aSTool->Search(ex.Current(), edgeL, Standard_True, Standard_True, Standard_True);
2988             if (!edgeL.IsNull())
2989               aShLS2.Append(edgeL);
2990             ex.Next();
2991           }
2992         }
2993         if (!aShL.IsNull())
2994           aShLS2.Append(aShL);
2995       }
2996     }
2997   }
2998
2999   if(!aShLS1.IsEmpty())
3000   {
3001     // add to XCAF
3002     if(!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
3003     {
3004       aGDTL = aDGTTool->AddDimension();
3005       myGDTMap.Bind(theEnt, aGDTL);
3006       aDGTTool->Lock(aGDTL);
3007       Handle(XCAFDoc_Dimension) aDim = XCAFDoc_Dimension::Set(aGDTL);
3008       TCollection_AsciiString aStr("DGT:Dimensional_");
3009       if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
3010       {
3011         aStr.AssignCat("Size");
3012       }
3013       else if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
3014       {
3015         aStr.AssignCat("Location");
3016       }
3017       TDataStd_Name::Set(aGDTL, aStr);
3018
3019       if(!aShLS2.IsEmpty())
3020       {
3021         aDGTTool->SetDimension(aShLS1, aShLS2, aGDTL);
3022       }
3023       else
3024       {
3025         TDF_LabelSequence aEmptySeq;
3026         aDGTTool->SetDimension(aShLS1, aEmptySeq, aGDTL);
3027       }
3028     }
3029     else
3030     {
3031       aGDTL = aDGTTool->AddGeomTolerance();
3032       myGDTMap.Bind(theEnt, aGDTL);
3033       aDGTTool->Lock(aGDTL);
3034       Handle(XCAFDoc_GeomTolerance) aGTol = XCAFDoc_GeomTolerance::Set(aGDTL);
3035       TCollection_AsciiString aStr("DGT:GeomTolerance");
3036       TDataStd_Name::Set(aGDTL, aStr);
3037       aDGTTool->SetGeomTolerance(aShLS1, aGDTL);
3038       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aGTol->GetObject();
3039       if(isAllAround)
3040         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Around);
3041       else if(isAllOver)
3042         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Over);
3043       aGTol->SetObject(anObj);
3044     }
3045
3046     if (aSemanticName)
3047     {
3048       TCollection_ExtendedString str(aSemanticName->String());
3049       TDataStd_Name::Set(aGDTL, str);
3050     }
3051
3052     readDatumsAP242(theEnt, aGDTL, theDoc, theWS);
3053   }
3054   return aGDTL;
3055 }
3056
3057 //=======================================================================
3058 //function : convertAngleValue
3059 //purpose  : auxilary
3060 //=======================================================================
3061 void convertAngleValue(
3062   const STEPConstruct_UnitContext& anUnitCtx,
3063   Standard_Real& aVal)
3064 {
3065   // convert radian to deg
3066   Standard_Real aFact = anUnitCtx.PlaneAngleFactor() * 180 / M_PI;
3067   // in order to avoid inaccuracy of calculation perform conversion
3068   // only if aFact not eqaul 1 with some precision
3069   if (fabs(1. - aFact) > Precision::Confusion())
3070   {
3071     aVal = aVal * aFact;
3072   }
3073 }
3074
3075
3076 //=======================================================================
3077 //function : setDimObjectToXCAF
3078 //purpose  : 
3079 //=======================================================================
3080 static void setDimObjectToXCAF(const Handle(Standard_Transient)& theEnt,
3081                                            const TDF_Label& aDimL,
3082                                            const Handle(TDocStd_Document)& theDoc,
3083                                            const Handle(XSControl_WorkSession)& theWS)
3084 {
3085   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
3086   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
3087   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
3088   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
3089   const Interface_Graph& aGraph = aTP->Graph();
3090   Handle(XCAFDimTolObjects_DimensionObject) aDimObj;
3091   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
3092     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) 
3093     return;
3094
3095   Handle(StepShape_DimensionalSize) aDimSize = 
3096     Handle(StepShape_DimensionalSize)::DownCast(theEnt);
3097   Handle(StepShape_DimensionalLocation) aDimLocation = 
3098     Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
3099
3100   aDimObj = new XCAFDimTolObjects_DimensionObject();
3101   Standard_Real aDim1=-1.,aDim2=-1.,aDim3=-1.;
3102   Standard_Boolean isPlusMinusTolerance = Standard_False;
3103   Handle(StepShape_TypeQualifier) aTQ;
3104   Handle(StepShape_ValueFormatTypeQualifier) aVFTQ;
3105   Handle(StepShape_ToleranceValue) aTV;
3106   Handle(StepShape_LimitsAndFits) aLAF;
3107   Handle(StepRepr_CompoundRepresentationItem) aCRI;
3108   Handle(StepGeom_Axis2Placement3d) anAP;
3109
3110   Interface_EntityIterator anIterDim;
3111   if(!aDimSize.IsNull())
3112   {
3113     anIterDim = aGraph.Sharings(aDimSize);
3114   }
3115   else
3116   {
3117     anIterDim = aGraph.Sharings(aDimLocation);
3118   }
3119   for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) {
3120     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR = 
3121       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anIterDim.Value());
3122     Handle(StepShape_PlusMinusTolerance) aPMT = 
3123       Handle(StepShape_PlusMinusTolerance)::DownCast(anIterDim.Value());
3124     if(!aDCR.IsNull()) {
3125       Handle(StepShape_ShapeDimensionRepresentation) aSDR = aDCR->Representation();
3126       if(!aSDR.IsNull()) {
3127         Handle(StepRepr_HArray1OfRepresentationItem) aHARI = aSDR->Items();
3128
3129         if(!aHARI.IsNull())
3130         {
3131           for(Standard_Integer nr = aHARI->Lower(); nr <= aHARI->Upper(); nr++)
3132           {
3133             Handle(StepRepr_RepresentationItem) aDRI = aHARI->Value(nr);
3134             if(aDRI.IsNull()) continue;
3135
3136             if (aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnit))) {
3137               // simple value / range
3138               Handle(StepRepr_ReprItemAndMeasureWithUnit) aMWU =
3139                 Handle(StepRepr_ReprItemAndMeasureWithUnit)::DownCast(aDRI);
3140               Standard_Real aVal = aMWU->GetMeasureWithUnit()->ValueComponent();
3141               StepBasic_Unit anUnit = aMWU->GetMeasureWithUnit()->UnitComponent();
3142               if (anUnit.IsNull()) 
3143                 continue;
3144               if (!(anUnit.CaseNum(anUnit.Value()) == 1)) 
3145                 continue;
3146               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3147               STEPConstruct_UnitContext anUnitCtx;
3148               anUnitCtx.ComputeFactors(NU);
3149               if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
3150                 aVal = aVal * anUnitCtx.LengthFactor();
3151               }
3152               else
3153                 if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit))) {
3154                   convertAngleValue(anUnitCtx, aVal);
3155                 }
3156               Handle(TCollection_HAsciiString) aName = aMWU->Name();
3157               if (aName->Search("upper") > 0) // upper limit
3158                 aDim2 = aVal;
3159               else // lower limit or simple nominal value
3160                 aDim1 = aVal;
3161             }
3162             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnitAndQRI))) {
3163               // value with qualifier (minimum/maximum/average)
3164               Handle(StepRepr_ReprItemAndMeasureWithUnitAndQRI) aMWU =
3165                 Handle(StepRepr_ReprItemAndMeasureWithUnitAndQRI)::DownCast(aDRI);
3166               Standard_Real aVal = aMWU->GetMeasureWithUnit()->ValueComponent();
3167               StepBasic_Unit anUnit = aMWU->GetMeasureWithUnit()->UnitComponent();
3168               if(anUnit.IsNull())
3169                 continue;
3170               if( !(anUnit.CaseNum(anUnit.Value()) == 1) )
3171                 continue;
3172               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3173               STEPConstruct_UnitContext anUnitCtx;
3174               anUnitCtx.ComputeFactors(NU);
3175               if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI))) {
3176                 aVal = aVal * anUnitCtx.LengthFactor();
3177               }
3178               else
3179                 if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI))) {
3180                   convertAngleValue(anUnitCtx, aVal);
3181                 }
3182               Handle(StepShape_QualifiedRepresentationItem) aQRI = aMWU->GetQualifiedRepresentationItem();
3183               if (aQRI->Qualifiers()->Length() == 0) {
3184                 aDim1 = aVal;
3185                 continue;
3186               }
3187               Handle(StepShape_TypeQualifier) aValueType = aQRI->Qualifiers()->Value(1).TypeQualifier();
3188               if (aValueType->Name()->String().IsEqual("minimum"))
3189                 aDim2 = aVal;
3190               else if (aValueType->Name()->String().IsEqual("maximum"))
3191                 aDim3 = aVal;
3192               else aDim1 = aVal;
3193             }
3194             else if(aDRI->IsKind(STANDARD_TYPE(StepShape_QualifiedRepresentationItem))) {
3195               //get qualifier
3196               Handle(StepShape_QualifiedRepresentationItem) aQRI =
3197                 Handle(StepShape_QualifiedRepresentationItem)::DownCast(aDRI);
3198               for(Standard_Integer l = 1; l <= aQRI->NbQualifiers(); l++)
3199               {
3200                 aTQ = aQRI->Qualifiers()->Value(l).TypeQualifier();
3201                 aVFTQ = aQRI->Qualifiers()->Value(l).ValueFormatTypeQualifier();
3202               }
3203             }
3204             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
3205               Handle(StepRepr_DescriptiveRepresentationItem) aDescription =
3206                 Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(aDRI);
3207               aDimObj->AddDescription(aDescription->Description(), aDescription->Name());
3208             }
3209             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_CompoundRepresentationItem))) {
3210               aCRI = Handle(StepRepr_CompoundRepresentationItem)::DownCast(aDRI);
3211             }
3212             else if(aDRI->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
3213             {
3214               anAP = Handle(StepGeom_Axis2Placement3d)::DownCast(aDRI);
3215             }
3216           }
3217         }
3218       }
3219     }
3220     else if (!aPMT.IsNull())
3221     {
3222       isPlusMinusTolerance = Standard_True;
3223       StepShape_ToleranceMethodDefinition aTMD = aPMT->Range();
3224       if(aPMT.IsNull()) continue;
3225       if(aTMD.CaseNumber() == 1)
3226         //! 1 -> ToleranceValue from StepShape
3227         //! 2 -> LimitsAndFits from StepShape
3228       {
3229         //plus minus tolerance 
3230         aTV = aTMD.ToleranceValue();
3231         if (aTV.IsNull()) continue;
3232
3233         Handle(StepBasic_MeasureWithUnit) aMWU = aTV->UpperBound();
3234         Standard_Real aVal = aTV->UpperBound()->ValueComponent();
3235         StepBasic_Unit anUnit = aTV->UpperBound()->UnitComponent();
3236         if(anUnit.IsNull()) continue;
3237         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3238         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3239         STEPConstruct_UnitContext anUnitCtx;
3240         anUnitCtx.ComputeFactors(NU);
3241         if (aMWU->IsKind(STANDARD_TYPE(StepBasic_LengthMeasureWithUnit)) ||
3242           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI)))
3243         {
3244           aVal = aVal * anUnitCtx.LengthFactor();
3245         }
3246         else if (aMWU->IsKind(STANDARD_TYPE(StepBasic_PlaneAngleMeasureWithUnit)) ||
3247           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI)))
3248         {
3249           convertAngleValue(anUnitCtx, aVal);
3250         }
3251         aDim3 = aVal;
3252
3253         aMWU = aTV->LowerBound();
3254         aVal = aTV->LowerBound()->ValueComponent();
3255         anUnit = aTV->LowerBound()->UnitComponent();
3256         if(anUnit.IsNull()) continue;
3257         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3258         NU = anUnit.NamedUnit();
3259         anUnitCtx.ComputeFactors(NU);