49c0472ba6de420177a29f7616fc5d53631cb0d0
[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       TDataStd_UAttribute::Set (InvLayerLab, XCAFDoc::InvisibleGUID());
1410     }
1411   }
1412   return Standard_True;
1413 }
1414
1415 //=======================================================================
1416 //function : ReadSHUOs
1417 //purpose  : 
1418 //=======================================================================
1419
1420 static Standard_Boolean findNextSHUOlevel(const Handle(XSControl_WorkSession) &WS,
1421   const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1422   const Handle(XCAFDoc_ShapeTool)& STool,
1423   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1424   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1425   TDF_LabelSequence& aLabels)
1426 {
1427   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1428   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1429   for (subs.Start(); subs.More(); subs.Next()) {
1430     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1431       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1432       break;
1433     }
1434   }
1435   if (subSHUO.IsNull())
1436     return Standard_False;
1437
1438   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = subSHUO->NextUsage();
1439   if (NUNAUO.IsNull())
1440     return Standard_False;
1441   //   Handle(Interface_InterfaceModel) Model = WS->Model();
1442   //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1443   //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1444   //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1445   //   if ( binder.IsNull() || ! binder->HasResult() )
1446   //     return Standard_False;
1447   //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1448     // get label of NAUO next level
1449   TDF_Label NULab;
1450   STEPConstruct_Tool Tool(WS);
1451   NULab = STEPCAFControl_Reader::FindInstance(NUNAUO, STool, Tool, ShapeLabelMap);
1452   //   STool->Search(NUSh, NUlab);
1453   if (NULab.IsNull())
1454     return Standard_False;
1455   aLabels.Append(NULab);
1456   // and check by recurse.
1457   findNextSHUOlevel(WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels);
1458   return Standard_True;
1459 }
1460
1461
1462 //=======================================================================
1463 //function : setSHUOintoDoc
1464 //purpose  : auxilary
1465 //=======================================================================
1466 static TDF_Label setSHUOintoDoc(const Handle(XSControl_WorkSession) &WS,
1467   const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1468   const Handle(XCAFDoc_ShapeTool)& STool,
1469   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1470   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1471 {
1472   TDF_Label aMainLabel;
1473   // get upper usage NAUO from SHUO.
1474   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1475     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1476   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = SHUO->NextUsage();
1477   if (UUNAUO.IsNull() || NUNAUO.IsNull()) {
1478 #ifdef OCCT_DEBUG
1479     cout << "Warning: " << __FILE__ << ": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
1480 #endif
1481     return aMainLabel;
1482   }
1483   //   Handle(Interface_InterfaceModel) Model = WS->Model();
1484   //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1485   //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1486   //   TopoDS_Shape UUSh, NUSh;
1487   //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1488   //   if ( binder.IsNull() || ! binder->HasResult() )
1489   //     return aMainLabel;
1490   //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1491   //   binder = TP->Find(NUNAUO);
1492   //   if ( binder.IsNull() || ! binder->HasResult() )
1493   //     return aMainLabel;
1494   //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1495
1496     // get first labels for first SHUO attribute
1497   TDF_Label UULab, NULab;
1498   STEPConstruct_Tool Tool(WS);
1499   UULab = STEPCAFControl_Reader::FindInstance(UUNAUO, STool, Tool, ShapeLabelMap);
1500   NULab = STEPCAFControl_Reader::FindInstance(NUNAUO, STool, Tool, ShapeLabelMap);
1501
1502   //   STool->Search(UUSh, UULab);
1503   //   STool->Search(NUSh, NULab);
1504   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1505   //create sequence fo labels to set SHUO structure into the document
1506   TDF_LabelSequence ShuoLabels;
1507   ShuoLabels.Append(UULab);
1508   ShuoLabels.Append(NULab);
1509   // add all other labels of sub SHUO entities
1510   findNextSHUOlevel(WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels);
1511   // last accord for SHUO
1512   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1513   if (STool->SetSHUO(ShuoLabels, anSHUOAttr))
1514     aMainLabel = anSHUOAttr->Label();
1515
1516   return aMainLabel;
1517 }
1518
1519
1520 //=======================================================================
1521 //function : ReadSHUOs
1522 //purpose  : 
1523 //=======================================================================
1524
1525 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs(const Handle(XSControl_WorkSession) &WS,
1526   Handle(TDocStd_Document)& Doc,
1527   const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1528   const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1529 {
1530   // the big part code duplication from ReadColors.
1531   // It is possible to share this code functionality, just to decide how ???
1532   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool(Doc->Main());
1533   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1534
1535   STEPConstruct_Styles Styles(WS);
1536   if (!Styles.LoadStyles()) {
1537 #ifdef OCCT_DEBUG
1538     cout << "Warning: no styles are found in the model" << endl;
1539 #endif
1540     return Standard_False;
1541   }
1542   // searching for invisible items in the model
1543   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1544   Styles.LoadInvisStyles(aHSeqOfInvisStyle);
1545   // parse and search for color attributes
1546   Standard_Integer nb = Styles.NbStyles();
1547   for (Standard_Integer i = 1; i <= nb; i++) {
1548     Handle(StepVisual_StyledItem) style = Styles.Style(i);
1549     if (style.IsNull()) continue;
1550
1551     Standard_Boolean IsVisible = Standard_True;
1552     // check the visibility of styled item.
1553     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++) {
1554       if (style != aHSeqOfInvisStyle->Value(si))
1555         continue;
1556       // found that current style is invisible.
1557 #ifdef OCCT_DEBUG
1558       cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
1559 #endif
1560       IsVisible = Standard_False;
1561       break;
1562     }
1563
1564     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
1565     // check if it is component style
1566     Standard_Boolean IsComponent = Standard_False;
1567     if (!Styles.GetColors(style, SurfCol, BoundCol, CurveCol, IsComponent) && IsVisible)
1568       continue;
1569     if (!IsComponent)
1570       continue;
1571     Handle(StepShape_ShapeRepresentation) aSR;
1572     findStyledSR(style, aSR);
1573     // search for SR along model
1574     if (aSR.IsNull())
1575       continue;
1576     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(aSR);
1577     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1578     for (subs.Start(); subs.More(); subs.Next()) {
1579       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1580       if (aSDR.IsNull())
1581         continue;
1582       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1583       Handle(StepRepr_ProductDefinitionShape) PDS =
1584         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1585       if (PDS.IsNull())
1586         continue;
1587       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1588       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1589         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1590       if (SHUO.IsNull())
1591         continue;
1592
1593       // set the SHUO structure to the document
1594       TDF_Label aLabelForStyle = setSHUOintoDoc(WS, SHUO, STool, PDFileMap, ShapeLabelMap);
1595       if (aLabelForStyle.IsNull()) {
1596 #ifdef OCCT_DEBUG
1597         cout << "Warning: " << __FILE__ << ": coudnot create SHUO structure in the document" << endl;
1598 #endif
1599         continue;
1600       }
1601       // now set the style to the SHUO main label.
1602       if (!SurfCol.IsNull()) {
1603         Quantity_Color col;
1604         Styles.DecodeColor(SurfCol, col);
1605         CTool->SetColor(aLabelForStyle, col, XCAFDoc_ColorSurf);
1606       }
1607       if (!BoundCol.IsNull()) {
1608         Quantity_Color col;
1609         Styles.DecodeColor(BoundCol, col);
1610         CTool->SetColor(aLabelForStyle, col, XCAFDoc_ColorCurv);
1611       }
1612       if (!CurveCol.IsNull()) {
1613         Quantity_Color col;
1614         Styles.DecodeColor(CurveCol, col);
1615         CTool->SetColor(aLabelForStyle, col, XCAFDoc_ColorCurv);
1616       }
1617       if (!IsVisible)
1618         // sets the invisibility for shape.
1619         CTool->SetVisibility(aLabelForStyle, Standard_False);
1620
1621     } // end search SHUO by SDR
1622   } // end iterates on styles
1623
1624   return Standard_True;
1625 }
1626
1627 //=======================================================================
1628 //function : GetMassConversionFactor
1629 //purpose  : 
1630 //=======================================================================
1631 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1632   Standard_Real& afact)
1633 {
1634   afact = 1.;
1635   if (!NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit))) return Standard_False;
1636   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1637     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1638   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1639   afact = MWUCBU->ValueComponent();
1640   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1641   if (anUnit2.CaseNum(anUnit2.Value()) == 1) {
1642     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1643     if (NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1644       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1645       if (SU->Name() == StepBasic_sunGram) {
1646         if (SU->HasPrefix())
1647           afact *= STEPConstruct_UnitContext::ConvertSiPrefix(SU->Prefix());
1648       }
1649     }
1650   }
1651   return Standard_True;
1652 }
1653
1654 //=======================================================================
1655 //function : readPMIPresentation
1656 //purpose  : read polyline or tessellated presentation for 
1657 // (Annotation_Curve_Occurrence or Draughting_Callout)
1658 //=======================================================================
1659 Standard_Boolean readPMIPresentation(const Handle(Standard_Transient)& thePresentEntity,
1660   const Handle(XSControl_TransferReader)& theTR,
1661   const Standard_Real theFact,
1662   TopoDS_Shape& thePresentation,
1663   Handle(TCollection_HAsciiString)& thePresentName,
1664   Bnd_Box& theBox)
1665 {
1666   if (thePresentEntity.IsNull())
1667     return Standard_False;
1668   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1669   Handle(StepVisual_AnnotationOccurrence) anAO;
1670   NCollection_Vector<Handle(StepVisual_StyledItem)> anAnnotations;
1671   if (thePresentEntity->IsKind(STANDARD_TYPE(StepVisual_AnnotationOccurrence)))
1672   {
1673     anAO = Handle(StepVisual_AnnotationOccurrence)::DownCast(thePresentEntity);
1674     if (!anAO.IsNull()) {
1675       thePresentName = anAO->Name();
1676       anAnnotations.Append(anAO);
1677     }
1678   }
1679   else if (thePresentEntity->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout)))
1680   {
1681     Handle(StepVisual_DraughtingCallout) aDCallout =
1682       Handle(StepVisual_DraughtingCallout)::DownCast(thePresentEntity);
1683     thePresentName = aDCallout->Name();
1684     for (Standard_Integer i = 1; i <= aDCallout->NbContents() && anAO.IsNull(); i++) {
1685       anAO = Handle(StepVisual_AnnotationOccurrence)::DownCast(aDCallout->ContentsValue(i).Value());
1686       if (!anAO.IsNull())
1687       {
1688         anAnnotations.Append(anAO);
1689         continue;
1690       }
1691       Handle(StepVisual_TessellatedAnnotationOccurrence) aTesselation =
1692         aDCallout->ContentsValue(i).TessellatedAnnotationOccurrence();
1693       if (!aTesselation.IsNull())
1694         anAnnotations.Append(aTesselation);
1695     }
1696   }
1697
1698   if (!anAnnotations.Length())
1699     return Standard_False;
1700
1701
1702   BRep_Builder aB;
1703   TopoDS_Compound aResAnnotation;
1704   aB.MakeCompound(aResAnnotation);
1705
1706   Standard_Integer i = 0;
1707   Bnd_Box aBox;
1708   Standard_Integer nbShapes = 0;
1709   for (; i < anAnnotations.Length(); i++)
1710   {
1711     Handle(StepVisual_StyledItem) anItem = anAnnotations(i);
1712     anAO = Handle(StepVisual_AnnotationOccurrence)::DownCast(anItem);
1713     TopoDS_Shape anAnnotationShape;
1714     if (!anAO.IsNull())
1715     {
1716       Handle(StepRepr_RepresentationItem) aCurveItem = anAO->Item();
1717       anAnnotationShape = STEPConstruct::FindShape(aTP, aCurveItem);
1718       if (anAnnotationShape.IsNull())
1719       {
1720         Handle(Transfer_Binder) binder = theTR->Actor()->Transfer(aCurveItem, aTP);
1721         if (!binder.IsNull() && binder->HasResult()) {
1722           anAnnotationShape = TransferBRep::ShapeResult(aTP, binder);
1723         }
1724       }
1725     }
1726     //case of tessellated entities
1727     else
1728     {
1729       Handle(StepRepr_RepresentationItem) aTessItem = anItem->Item();
1730       if (aTessItem.IsNull())
1731         continue;
1732       Handle(StepVisual_TessellatedGeometricSet) aTessSet = Handle(StepVisual_TessellatedGeometricSet)::DownCast(aTessItem);
1733       if (aTessSet.IsNull())
1734         continue;
1735       NCollection_Handle<StepVisual_Array1OfTessellatedItem> aListItems = aTessSet->Items();
1736       Standard_Integer nb = aListItems.IsNull() ? 0 : aListItems->Length();
1737       Handle(StepVisual_TessellatedCurveSet) aTessCurve;
1738       for (Standard_Integer n = 1; n <= nb && aTessCurve.IsNull(); n++)
1739       {
1740         aTessCurve = Handle(StepVisual_TessellatedCurveSet)::DownCast(aListItems->Value(n));
1741       }
1742       if (aTessCurve.IsNull())
1743         continue;
1744       Handle(StepVisual_CoordinatesList) aCoordList = aTessCurve->CoordList();
1745       if (aCoordList.IsNull())
1746         continue;
1747       Handle(TColgp_HArray1OfXYZ)  aPoints = aCoordList->Points();
1748
1749       if (aPoints.IsNull() || aPoints->Length() == 0)
1750         continue;
1751       NCollection_Handle<StepVisual_VectorOfHSequenceOfInteger> aCurves = aTessCurve->Curves();
1752       Standard_Integer aNbC = (aCurves.IsNull() ? 0 : aCurves->Length());
1753       TopoDS_Compound aComp;
1754       aB.MakeCompound(aComp);
1755
1756       Standard_Integer k = 0;
1757       for (; k < aNbC; k++)
1758       {
1759         Handle(TColStd_HSequenceOfInteger) anIndexes = aCurves->Value(k);
1760         TopoDS_Wire aCurW;
1761         aB.MakeWire(aCurW);
1762
1763         for (Standard_Integer n = 1; n < anIndexes->Length(); n++)
1764         {
1765           Standard_Integer ind = anIndexes->Value(n);
1766           Standard_Integer indnext = anIndexes->Value(n + 1);
1767           if (ind > aPoints->Length() || indnext > aPoints->Length())
1768             continue;
1769           gp_Pnt aP1(aPoints->Value(ind) * theFact);
1770           gp_Pnt aP2(aPoints->Value(indnext) * theFact);
1771           BRepBuilderAPI_MakeEdge aMaker(aP1, aP2);
1772           if (aMaker.IsDone())
1773           {
1774             TopoDS_Edge aCurE = aMaker.Edge();
1775             aB.Add(aCurW, aCurE);
1776           }
1777         }
1778         aB.Add(aComp, aCurW);
1779       }
1780       anAnnotationShape = aComp;
1781     }
1782     if (!anAnnotationShape.IsNull())
1783     {
1784       nbShapes++;
1785       aB.Add(aResAnnotation, anAnnotationShape);
1786       if (i == anAnnotations.Length() - 1)
1787         BRepBndLib::AddClose(anAnnotationShape, aBox);
1788     }
1789   }
1790
1791   thePresentation = aResAnnotation;
1792   theBox = aBox;
1793   return (nbShapes > 0);
1794 }
1795
1796 //=======================================================================
1797 //function : readAnnotationPlane
1798 //purpose  : read annotation plane
1799 //=======================================================================
1800 Standard_Boolean readAnnotationPlane(const Handle(StepVisual_AnnotationPlane) theAnnotationPlane,
1801   gp_Ax2& thePlane)
1802 {
1803   if (theAnnotationPlane.IsNull())
1804     return Standard_False;
1805   Handle(StepRepr_RepresentationItem) aPlaneItem = theAnnotationPlane->Item();
1806   if (aPlaneItem.IsNull())
1807     return Standard_False;
1808   Handle(StepGeom_Axis2Placement3d) aA2P3D;
1809   //retrieve axes from AnnotationPlane
1810   if (aPlaneItem->IsKind(STANDARD_TYPE(StepGeom_Plane))) {
1811     Handle(StepGeom_Plane) aPlane = Handle(StepGeom_Plane)::DownCast(aPlaneItem);
1812     aA2P3D = aPlane->Position();
1813   }
1814   else if (aPlaneItem->IsKind(STANDARD_TYPE(StepVisual_PlanarBox))) {
1815     Handle(StepVisual_PlanarBox) aBox = Handle(StepVisual_PlanarBox)::DownCast(aPlaneItem);
1816     aA2P3D = aBox->Placement().Axis2Placement3d();
1817   }
1818   if (aA2P3D.IsNull())
1819     return Standard_False;
1820
1821   Handle(Geom_Axis2Placement) anAxis = StepToGeom::MakeAxis2Placement(aA2P3D);
1822   thePlane = anAxis->Ax2();
1823   return Standard_True;
1824 }
1825
1826 //=======================================================================
1827 //function : readAnnotation
1828 //purpose  : read annotation plane and position for given GDT
1829 // (Dimension, Geometric_Tolerance, Datum_Feature or Placed_Datum_Target_Feature)
1830 //=======================================================================
1831 void readAnnotation(const Handle(XSControl_TransferReader)& theTR,
1832   const Handle(Standard_Transient)& theGDT,
1833   const Handle(Standard_Transient)& theDimObject)
1834 {
1835   if (theGDT.IsNull() || theDimObject.IsNull())
1836     return;
1837   Handle(TCollection_HAsciiString) aPresentName;
1838   TopoDS_Compound aResAnnotation;
1839   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1840   const Interface_Graph& aGraph = aTP->Graph();
1841   // find the proper DraughtingModelItemAssociation
1842   Interface_EntityIterator subs = aGraph.Sharings(theGDT);
1843   Handle(StepAP242_DraughtingModelItemAssociation) aDMIA;
1844   for (subs.Start(); subs.More() && aDMIA.IsNull(); subs.Next()) {
1845     if (!subs.Value()->IsKind(STANDARD_TYPE(StepAP242_DraughtingModelItemAssociation)))
1846       continue;
1847     aDMIA = Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(subs.Value());
1848     Handle(TCollection_HAsciiString) aName = aDMIA->Name();
1849     aName->LowerCase();
1850     if (!aName->Search(new TCollection_HAsciiString("pmi representation to presentation link"))) {
1851       aDMIA = NULL;
1852     }
1853   }
1854   if (aDMIA.IsNull() || aDMIA->NbIdentifiedItem() == 0)
1855     return;
1856
1857   // calculate units
1858   Handle(StepVisual_DraughtingModel) aDModel =
1859     Handle(StepVisual_DraughtingModel)::DownCast(aDMIA->UsedRepresentation());
1860   XSAlgo::AlgoContainer()->PrepareForTransfer();
1861   STEPControl_ActorRead anActor;
1862   anActor.PrepareUnits(aDModel, aTP);
1863   Standard_Real aFact = UnitsMethods::LengthFactor();
1864
1865   // retrieve AnnotationPlane
1866   Handle(StepRepr_RepresentationItem) aDMIAE = aDMIA->IdentifiedItemValue(1);
1867   if (aDMIAE.IsNull())
1868     return;
1869   gp_Ax2 aPlaneAxes;
1870   subs = aGraph.Sharings(aDMIAE);
1871   Handle(StepVisual_AnnotationPlane) anAnPlane;
1872   for (subs.Start(); subs.More() && anAnPlane.IsNull(); subs.Next()) {
1873     anAnPlane = Handle(StepVisual_AnnotationPlane)::DownCast(subs.Value());
1874   }
1875   Standard_Boolean isHasPlane = readAnnotationPlane(anAnPlane, aPlaneAxes);
1876
1877   // set plane axes to XCAF
1878   if (isHasPlane) {
1879     if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1880       Handle(XCAFDimTolObjects_DimensionObject) anObj =
1881         Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1882       Handle(TColgp_HArray1OfPnt) aPnts = new TColgp_HArray1OfPnt(1, 1);
1883       anObj->SetPlane(aPlaneAxes);
1884     }
1885     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1886       Handle(XCAFDimTolObjects_DatumObject) anObj =
1887         Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1888       anObj->SetPlane(aPlaneAxes);
1889     }
1890     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1891       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1892         Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1893       anObj->SetPlane(aPlaneAxes);
1894     }
1895   }
1896
1897   // Retrieve presentation
1898   Bnd_Box aBox;
1899   if (!readPMIPresentation(aDMIAE, theTR, aFact, aResAnnotation, aPresentName, aBox))
1900     return;
1901   gp_Pnt aPtext(0., 0., 0.);
1902   // if Annotation plane location inside bounding box set it to text position
1903   // else set the center of bounding box to text position 0027372
1904   if (!aBox.IsVoid())
1905   {
1906     Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
1907     aBox.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
1908     if (isHasPlane && !aBox.IsOut(aPlaneAxes.Location())) {
1909       aPtext = aPlaneAxes.Location();
1910     }
1911     else {
1912       aPtext = gp_Pnt((aXmin + aXmax) * 0.5, (aYmin + aYmax) * 0.5, (aZmin + aZmax) * 0.5);
1913     }
1914   }
1915   else {
1916     aPtext = aPlaneAxes.Location();
1917   }
1918
1919   // set point to XCAF
1920   if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1921     Handle(XCAFDimTolObjects_DimensionObject) anObj =
1922       Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1923     anObj->SetPointTextAttach(aPtext);
1924     anObj->SetPresentation(aResAnnotation, aPresentName);
1925   }
1926   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1927     Handle(XCAFDimTolObjects_DatumObject) anObj =
1928       Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1929     anObj->SetPointTextAttach(aPtext);
1930     anObj->SetPresentation(aResAnnotation, aPresentName);
1931   }
1932   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1933     Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1934       Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1935     anObj->SetPointTextAttach(aPtext);
1936     anObj->SetPresentation(aResAnnotation, aPresentName);
1937   }
1938   return;
1939 }
1940
1941 //=======================================================================
1942 //function : readConnectionPoints
1943 //purpose  : read connection points for given dimension
1944 //=======================================================================
1945 void readConnectionPoints(const Handle(XSControl_TransferReader)& theTR,
1946   const Handle(Standard_Transient) theGDT,
1947   const Handle(XCAFDimTolObjects_DimensionObject)& theDimObject)
1948 {
1949   if (theGDT.IsNull() || theDimObject.IsNull())
1950     return;
1951   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1952   const Interface_Graph& aGraph = aTP->Graph();
1953
1954   
1955   Standard_Real aFact = 1.;
1956
1957   Handle(StepShape_ShapeDimensionRepresentation) aSDR = NULL;
1958   for (Interface_EntityIterator anIt = aGraph.Sharings(theGDT); aSDR.IsNull() && anIt.More(); anIt.Next()) {
1959     Handle(Standard_Transient) anEnt = anIt.Value();
1960     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR =
1961       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anEnt);
1962     if (!aDCR.IsNull())
1963       aSDR = !aDCR.IsNull() ? aDCR->Representation() : Handle(StepShape_ShapeDimensionRepresentation)::DownCast(anEnt);
1964   }
1965   if (!aSDR.IsNull())
1966   {
1967     XSAlgo::AlgoContainer()->PrepareForTransfer();
1968     STEPControl_ActorRead anActor;
1969     anActor.PrepareUnits(aSDR, aTP);
1970     aFact = UnitsMethods::LengthFactor();
1971   }
1972   
1973   if (theGDT->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
1974     // retrieve derived geometry
1975     Handle(StepShape_DimensionalSize) aDim = Handle(StepShape_DimensionalSize)::DownCast(theGDT);
1976     Handle(StepRepr_DerivedShapeAspect) aDSA = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->AppliesTo());
1977     if (aDSA.IsNull())
1978       return;
1979     Handle(StepAP242_GeometricItemSpecificUsage) aGISU = NULL;
1980     for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA); aGISU.IsNull() && anIt.More(); anIt.Next()) {
1981       aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
1982     }
1983     if (aGISU.IsNull() || aGISU->NbIdentifiedItem() == 0)
1984       return;
1985     Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU->IdentifiedItem()->Value(1));
1986     if (aPoint.IsNull()) {
1987       // try Axis2Placement3d.location instead of CartesianPoint
1988       Handle(StepGeom_Axis2Placement3d) anA2P3D =
1989         Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU->IdentifiedItem()->Value(1));
1990       if (anA2P3D.IsNull())
1991         return;
1992       aPoint = anA2P3D->Location();
1993     }
1994
1995     // set connection point to object
1996     gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
1997     theDimObject->SetPoint(aPnt);
1998   }
1999   else if (theGDT->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2000     // retrieve derived geometry
2001     Handle(StepShape_DimensionalLocation) aDim = Handle(StepShape_DimensionalLocation)::DownCast(theGDT);
2002     Handle(StepRepr_DerivedShapeAspect) aDSA1 = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->RelatingShapeAspect());
2003     Handle(StepRepr_DerivedShapeAspect) aDSA2 = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->RelatedShapeAspect());
2004     if (aDSA1.IsNull() && aDSA2.IsNull())
2005       return;
2006     Handle(StepAP242_GeometricItemSpecificUsage) aGISU1 = NULL;
2007     Handle(StepAP242_GeometricItemSpecificUsage) aGISU2 = NULL;
2008     if (!aDSA1.IsNull()) {
2009       for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA1); aGISU1.IsNull() && anIt.More(); anIt.Next()) {
2010         aGISU1 = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2011       }
2012     }
2013     if (!aDSA2.IsNull()) {
2014       for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA2); aGISU2.IsNull() && anIt.More(); anIt.Next()) {
2015         aGISU2 = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2016       }
2017     }
2018     // first point
2019     if (!aGISU1.IsNull() && aGISU1->NbIdentifiedItem() > 0) {
2020       Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU1->IdentifiedItem()->Value(1));
2021       if (aPoint.IsNull()) {
2022         // try Axis2Placement3d.location instead of CartesianPoint
2023         Handle(StepGeom_Axis2Placement3d) anA2P3D =
2024           Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU1->IdentifiedItem()->Value(1));
2025         if (!anA2P3D.IsNull())
2026           aPoint = anA2P3D->Location();
2027       }
2028       if (!aPoint.IsNull()) {
2029         // set connection point to object
2030         gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2031         theDimObject->SetPoint(aPnt);
2032       }
2033     }
2034     // second point
2035     if (!aGISU2.IsNull() && aGISU2->NbIdentifiedItem() > 0) {
2036       Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU2->IdentifiedItem()->Value(1));
2037       if (aPoint.IsNull()) {
2038         // try Axis2Placement3d.location instead of CartesianPoint
2039         Handle(StepGeom_Axis2Placement3d) anA2P3D =
2040           Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU2->IdentifiedItem()->Value(1));
2041         if (!anA2P3D.IsNull())
2042           aPoint = anA2P3D->Location();
2043       }
2044       if (!aPoint.IsNull()) {
2045         // set connection point to object
2046         gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2047         theDimObject->SetPoint2(aPnt);
2048       }
2049     }
2050   }
2051 }
2052
2053 //=======================================================================
2054 //function : ReadDatums
2055 //purpose  : auxilary
2056 //=======================================================================
2057 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
2058   const Handle(XCAFDoc_DimTolTool) &DGTTool,
2059   const Interface_Graph &graph,
2060   const Handle(Transfer_TransientProcess) &TP,
2061   const TDF_Label TolerL,
2062   const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
2063 {
2064   if (GTWDR.IsNull()) return Standard_False;
2065   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
2066   if (HADR.IsNull()) return Standard_False;
2067   for (Standard_Integer idr = 1; idr <= HADR->Length(); idr++) {
2068     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
2069     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
2070     if (aDatum.IsNull()) continue;
2071     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
2072     for (subs4.Start(); subs4.More(); subs4.Next()) {
2073       Handle(StepRepr_ShapeAspectRelationship) SAR =
2074         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
2075       if (SAR.IsNull()) continue;
2076       Handle(StepDimTol_DatumFeature) DF =
2077         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
2078       if (DF.IsNull()) continue;
2079       Interface_EntityIterator subs5 = graph.Sharings(DF);
2080       Handle(StepRepr_PropertyDefinition) PropDef;
2081       for (subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
2082         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
2083       }
2084       if (PropDef.IsNull()) continue;
2085       Handle(StepShape_AdvancedFace) AF;
2086       subs5 = graph.Sharings(PropDef);
2087       for (subs5.Start(); subs5.More(); subs5.Next()) {
2088         Handle(StepShape_ShapeDefinitionRepresentation) SDR =
2089           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
2090         if (!SDR.IsNull()) {
2091           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2092           if (!Repr.IsNull() && Repr->NbItems() > 0) {
2093             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
2094             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2095           }
2096         }
2097       }
2098       if (AF.IsNull()) return Standard_False;
2099       Standard_Integer index = TP->MapIndex(AF);
2100       TopoDS_Shape aSh;
2101       if (index > 0) {
2102         Handle(Transfer_Binder) binder = TP->MapItem(index);
2103         aSh = TransferBRep::ShapeResult(binder);
2104       }
2105       if (aSh.IsNull()) continue;
2106       TDF_Label shL;
2107       if (!STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True)) continue;
2108       DGTTool->SetDatum(shL, TolerL, PropDef->Name(), PropDef->Description(), aDatum->Identification());
2109     }
2110   }
2111   return Standard_True;
2112 }
2113
2114 //=======================================================================
2115 //function : FindShapeIndexForDGT
2116 //purpose  : auxiliary find shape index in map og imported shapes
2117 //=======================================================================
2118 static Standard_Integer FindShapeIndexForDGT(const Handle(Standard_Transient)& theEnt,
2119   const Handle(XSControl_WorkSession)& theWS)
2120 {
2121   const Handle(Transfer_TransientProcess) &aTP = theWS->TransferReader()->TransientProcess();
2122   // try to find index of given entity
2123   Standard_Integer anIndex = aTP->MapIndex(theEnt);
2124   if (anIndex > 0)
2125     return anIndex;
2126   // if theEnt is a geometry item try to find its topological item
2127   const Interface_Graph& aGraph = aTP->Graph();
2128   Interface_EntityIterator anIter = aGraph.Sharings(theEnt);
2129   for (anIter.Start(); anIter.More(); anIter.Next()) {
2130     if (anIter.Value()->IsKind(STANDARD_TYPE(StepShape_TopologicalRepresentationItem)))
2131     {
2132       anIndex = aTP->MapIndex(anIter.Value());
2133       if (anIndex > 0)
2134         return anIndex;
2135     }
2136   }
2137   return 0;
2138 }
2139
2140 //=======================================================================
2141 //function : collectShapeAspect
2142 //purpose  : 
2143 //=======================================================================
2144 static void collectShapeAspect(const Handle(StepRepr_ShapeAspect)& theSA,
2145   const Handle(XSControl_WorkSession)& theWS,
2146   NCollection_Sequence<Handle(StepRepr_ShapeAspect)>& theSAs)
2147 {
2148   if (theSA.IsNull())
2149     return;
2150   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2151   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2152   const Interface_Graph& aGraph = aTP->Graph();
2153   // Retrieve Shape_Aspect, connected to Representation_Item from Derived_Shape_Aspect
2154   if (theSA->IsKind(STANDARD_TYPE(StepRepr_DerivedShapeAspect))) {
2155     Interface_EntityIterator anIter = aGraph.Sharings(theSA);
2156     Handle(StepRepr_ShapeAspectDerivingRelationship) aSADR = NULL;
2157     for (; aSADR.IsNull() && anIter.More(); anIter.Next()) {
2158       aSADR = Handle(StepRepr_ShapeAspectDerivingRelationship)::DownCast(anIter.Value());
2159     }
2160     if (!aSADR.IsNull())
2161       collectShapeAspect(aSADR->RelatedShapeAspect(), theWS, theSAs);
2162   }
2163   else if (theSA->IsKind(STANDARD_TYPE(StepDimTol_DatumFeature)) ||
2164     theSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget))) {
2165     theSAs.Append(theSA);
2166     return;
2167   }
2168   else {
2169     // Find all children Shape_Aspect
2170     Standard_Boolean isSimple = Standard_True;
2171     Interface_EntityIterator anIter = aGraph.Sharings(theSA);
2172     for (; anIter.More(); anIter.Next()) {
2173       if (anIter.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship)) &&
2174         !anIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2175         Handle(StepRepr_ShapeAspectRelationship) aSAR =
2176           Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIter.Value());
2177         if (aSAR->RelatingShapeAspect() == theSA && !aSAR->RelatedShapeAspect().IsNull()
2178           && !aSAR->RelatedShapeAspect()->IsKind(STANDARD_TYPE(StepDimTol_Datum))) {
2179           collectShapeAspect(aSAR->RelatedShapeAspect(), theWS, theSAs);
2180           isSimple = Standard_False;
2181         }
2182       }
2183     }
2184     // If not Composite_Shape_Aspect (or subtype) append to sequence.
2185     if (isSimple)
2186       theSAs.Append(theSA);
2187   }
2188 }
2189
2190 //=======================================================================
2191 //function : getShapeLabel
2192 //purpose  : 
2193 //=======================================================================
2194
2195 static TDF_Label getShapeLabel(const Handle(StepRepr_RepresentationItem)& theItem,
2196   const Handle(XSControl_WorkSession)& theWS,
2197   const Handle(XCAFDoc_ShapeTool)& theShapeTool)
2198 {
2199   TDF_Label aShapeL;
2200   const Handle(Transfer_TransientProcess) &aTP = theWS->TransferReader()->TransientProcess();
2201   Standard_Integer index = FindShapeIndexForDGT(theItem, theWS);
2202   TopoDS_Shape aShape;
2203   if (index > 0) {
2204     Handle(Transfer_Binder) aBinder = aTP->MapItem(index);
2205     aShape = TransferBRep::ShapeResult(aBinder);
2206   }
2207   if (aShape.IsNull())
2208     return aShapeL;
2209   theShapeTool->Search(aShape, aShapeL, Standard_True, Standard_True, Standard_True);
2210   return aShapeL;
2211 }
2212
2213 //=======================================================================
2214 //function : setDatumToXCAF
2215 //purpose  : 
2216 //=======================================================================
2217
2218 Standard_Boolean STEPCAFControl_Reader::setDatumToXCAF(const Handle(StepDimTol_Datum)& theDat,
2219   const TDF_Label theGDTL,
2220   const Standard_Integer thePositionCounter,
2221   const XCAFDimTolObjects_DatumModifiersSequence& theXCAFModifiers,
2222   const XCAFDimTolObjects_DatumModifWithValue theXCAFModifWithVal,
2223   const Standard_Real theModifValue,
2224   const Handle(TDocStd_Document)& theDoc,
2225   const Handle(XSControl_WorkSession)& theWS)
2226 {
2227   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
2228   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
2229   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2230   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2231   const Interface_Graph& aGraph = aTP->Graph();
2232   Handle(XCAFDoc_Datum) aDat;
2233   TDF_LabelSequence aShapeLabels;
2234   Handle(XCAFDimTolObjects_DatumObject) aDatObj = new XCAFDimTolObjects_DatumObject();
2235
2236   // Collect all links to shapes
2237   NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2238   Interface_EntityIterator anIterD = aGraph.Sharings(theDat);
2239   for (anIterD.Start(); anIterD.More(); anIterD.Next()) {
2240     Handle(StepRepr_ShapeAspectRelationship) aSAR = Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterD.Value());
2241     if (aSAR.IsNull() || aSAR->RelatingShapeAspect().IsNull())
2242       continue;
2243     collectShapeAspect(aSAR->RelatingShapeAspect(), theWS, aSAs);
2244     Handle(StepDimTol_DatumFeature) aDF = Handle(StepDimTol_DatumFeature)::DownCast(aSAR->RelatingShapeAspect());
2245     if (!aSAR->RelatingShapeAspect()->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)))
2246       readAnnotation(aTR, aSAR->RelatingShapeAspect(), aDatObj);
2247   }
2248
2249   // Collect shape labels
2250   for (Standard_Integer i = 1; i <= aSAs.Length(); i++) {
2251     Handle(StepRepr_ShapeAspect) aSA = aSAs.Value(i);
2252     if (aSA.IsNull())
2253       continue;
2254     // Skip datum targets
2255     if (aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)))
2256       continue;
2257
2258     // Process all connected GISU
2259     Interface_EntityIterator anIter = aGraph.Sharings(aSA);
2260     for (; anIter.More(); anIter.Next()) {
2261       Handle(StepAP242_GeometricItemSpecificUsage) aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIter.Value());
2262       if (aGISU.IsNull())
2263         continue;
2264       for (Standard_Integer j = 1; j <= aGISU->NbIdentifiedItem(); j++) {
2265         TDF_Label aShapeL = getShapeLabel(aGISU->IdentifiedItemValue(j), theWS, aSTool);
2266         if (!aShapeL.IsNull())
2267           aShapeLabels.Append(aShapeL);
2268       }
2269     }
2270   }
2271
2272   // Process datum targets and create objects for them
2273   Standard_Boolean isExistDatumTarget = Standard_False;
2274   for (Standard_Integer i = 1; i <= aSAs.Length(); i++) {
2275     Handle(StepDimTol_PlacedDatumTargetFeature) aDT = Handle(StepDimTol_PlacedDatumTargetFeature)::DownCast(aSAs.Value(i));
2276     if (aDT.IsNull())
2277       continue;
2278     Handle(XCAFDimTolObjects_DatumObject) aDatTargetObj = new XCAFDimTolObjects_DatumObject();
2279     XCAFDimTolObjects_DatumTargetType aType;
2280     if (!STEPCAFControl_GDTProperty::GetDatumTargetType(aDT->Description(), aType))
2281       continue;
2282     aDatTargetObj->SetDatumTargetType(aType);
2283     Standard_Boolean isValidDT = Standard_False;
2284
2285     // Feature for datum target
2286     TDF_LabelSequence aDTShapeLabels;
2287     Interface_EntityIterator aDTIter = aGraph.Sharings(aDT);
2288     Handle(StepRepr_FeatureForDatumTargetRelationship) aRelationship;
2289     for (; aDTIter.More() && aRelationship.IsNull(); aDTIter.Next()) {
2290       aRelationship = Handle(StepRepr_FeatureForDatumTargetRelationship)::DownCast(aDTIter.Value());
2291     }
2292     if (!aRelationship.IsNull()) {
2293       Handle(StepRepr_ShapeAspect) aSA = aRelationship->RelatingShapeAspect();
2294       Interface_EntityIterator aSAIter = aGraph.Sharings(aSA);
2295       for (; aSAIter.More(); aSAIter.Next()) {
2296         Handle(StepAP242_GeometricItemSpecificUsage) aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(aSAIter.Value());
2297         if (aGISU.IsNull())
2298           continue;
2299         for (Standard_Integer j = 1; j <= aGISU->NbIdentifiedItem(); j++) {
2300           TDF_Label aShapeL = getShapeLabel(aGISU->IdentifiedItemValue(j), theWS, aSTool);
2301           if (!aShapeL.IsNull()) {
2302             aDTShapeLabels.Append(aShapeL);
2303             isValidDT = Standard_True;
2304           }
2305         }
2306       }
2307     }
2308
2309     if (aType != XCAFDimTolObjects_DatumTargetType_Area && !isValidDT) {
2310       // Try another way of feature connection
2311       for (aDTIter.Start(); aDTIter.More(); aDTIter.Next()) {
2312         Handle(StepAP242_GeometricItemSpecificUsage) aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(aDTIter.Value());
2313         if (aGISU.IsNull())
2314           continue;
2315         for (Standard_Integer j = 1; j <= aGISU->NbIdentifiedItem(); j++) {
2316           TDF_Label aShapeL = getShapeLabel(aGISU->IdentifiedItemValue(j), theWS, aSTool);
2317           if (!aShapeL.IsNull()) {
2318             aDTShapeLabels.Append(aShapeL);
2319             isValidDT = Standard_True;
2320           }
2321         }
2322       }
2323     }
2324
2325     if (aType == XCAFDimTolObjects_DatumTargetType_Area) {
2326       // Area datum target
2327       Interface_EntityIterator anIterDTF = aGraph.Shareds(aDT);
2328       Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2329       for (; anIterDTF.More() && aGISU.IsNull(); anIterDTF.Next()) {
2330         aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDTF.Value());
2331       }
2332       Handle(StepRepr_RepresentationItem) anItem;
2333       if (aGISU->NbIdentifiedItem() > 0)
2334         anItem = aGISU->IdentifiedItemValue(1);
2335       if (anItem.IsNull())
2336         continue;
2337       Standard_Integer anItemIndex = FindShapeIndexForDGT(anItem, theWS);
2338       if (anItemIndex > 0) {
2339         Handle(Transfer_Binder) aBinder = aTP->MapItem(anItemIndex);
2340         TopoDS_Shape anItemShape = TransferBRep::ShapeResult(aBinder);
2341         aDatTargetObj->SetDatumTarget(anItemShape);
2342         isValidDT = Standard_True;
2343       }
2344     }
2345     else {
2346       // Point/line/rectangle/circle datum targets 
2347       Interface_EntityIterator anIter = aGraph.Sharings(aDT);
2348       Handle(StepRepr_PropertyDefinition) aPD;
2349       for (; anIter.More() && aPD.IsNull(); anIter.Next()) {
2350         aPD = Handle(StepRepr_PropertyDefinition)::DownCast(anIter.Value());
2351       }
2352       if (!aPD.IsNull()) {
2353         anIter = aGraph.Sharings(aPD);
2354         Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
2355         for (; anIter.More() && aSDR.IsNull(); anIter.Next()) {
2356           aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(anIter.Value());
2357         }
2358         if (!aSDR.IsNull()) {
2359           Handle(StepShape_ShapeRepresentationWithParameters) aSRWP
2360             = Handle(StepShape_ShapeRepresentationWithParameters)::DownCast(aSDR->UsedRepresentation());
2361           if (!aSRWP.IsNull()) {
2362             isValidDT = Standard_True;
2363             // Collect parameters of datum target
2364             for (Standard_Integer j = aSRWP->Items()->Lower(); j <= aSRWP->Items()->Upper(); j++)
2365             {
2366               if (aSRWP->ItemsValue(j).IsNull())
2367                 continue;
2368               if (aSRWP->ItemsValue(j)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2369               {
2370                 Handle(StepGeom_Axis2Placement3d) anAx
2371                   = Handle(StepGeom_Axis2Placement3d)::DownCast(aSRWP->ItemsValue(j));
2372                 XSAlgo::AlgoContainer()->PrepareForTransfer();
2373                 STEPControl_ActorRead anActor;
2374                 anActor.PrepareUnits(aSRWP, aTP);
2375                 Handle(Geom_Axis2Placement) anAxis = StepToGeom::MakeAxis2Placement(anAx);
2376                 aDatTargetObj->SetDatumTargetAxis(anAxis->Ax2());
2377               }
2378               else if (aSRWP->ItemsValue(j)->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit)))
2379               {
2380                 Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aM =
2381                   Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aSRWP->ItemsValue(j));
2382                 Standard_Real aVal = aM->GetMeasureWithUnit()->ValueComponent();
2383                 StepBasic_Unit anUnit = aM->GetMeasureWithUnit()->UnitComponent();
2384                 if (anUnit.IsNull())
2385                   continue;
2386                 Handle(StepBasic_NamedUnit) aNU = anUnit.NamedUnit();
2387                 if (aNU.IsNull())
2388                   continue;
2389                 STEPConstruct_UnitContext anUnitCtx;
2390                 anUnitCtx.ComputeFactors(aNU);
2391                 aVal = aVal * anUnitCtx.LengthFactor();
2392                 if (aM->Name()->String().IsEqual("target length") ||
2393                   aM->Name()->String().IsEqual("target diameter"))
2394                   aDatTargetObj->SetDatumTargetLength(aVal);
2395                 else
2396                   aDatTargetObj->SetDatumTargetWidth(aVal);
2397               }
2398             }
2399           }
2400         }
2401       }
2402     }
2403
2404     // Create datum target object
2405     if (isValidDT) {
2406       TDF_Label aDatL = aDGTTool->AddDatum();
2407       myGDTMap.Bind(aDT, aDatL);
2408       aDGTTool->Lock(aDatL);
2409       aDat = XCAFDoc_Datum::Set(aDatL);
2410       aDGTTool->SetDatum(aDTShapeLabels, aDatL);
2411       aDatTargetObj->SetName(theDat->Identification());
2412       aDatTargetObj->SetPosition(thePositionCounter);
2413       if (!theXCAFModifiers.IsEmpty())
2414         aDatTargetObj->SetModifiers(theXCAFModifiers);
2415       if (theXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None)
2416         aDatTargetObj->SetModifierWithValue(theXCAFModifWithVal, theModifValue);
2417       aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2418       aDatTargetObj->IsDatumTarget(Standard_True);
2419       aDatTargetObj->SetDatumTargetNumber(aDT->TargetId()->IntegerValue());
2420       readAnnotation(aTR, aDT, aDatTargetObj);
2421       aDat->SetObject(aDatTargetObj);
2422       isExistDatumTarget = Standard_True;
2423     }
2424   }
2425
2426   if (aShapeLabels.Length() > 0 || !isExistDatumTarget) {
2427     // Create object for datum
2428     TDF_Label aDatL = aDGTTool->AddDatum();
2429     myGDTMap.Bind(theDat, aDatL);
2430     // bind datum label with all reference datum_feature entities
2431     for (Standard_Integer i = 1; i <= aSAs.Length(); i++) {
2432       Handle(StepRepr_ShapeAspect) aSA = aSAs.Value(i);
2433       if (aSA.IsNull() || aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)))
2434         continue;
2435       myGDTMap.Bind(aSA, aDatL);
2436     }
2437     aDGTTool->Lock(aDatL);
2438     aDat = XCAFDoc_Datum::Set(aDatL);
2439     aDGTTool->SetDatum(aShapeLabels, aDatL);
2440     aDatObj->SetName(theDat->Identification());
2441     aDatObj->SetPosition(thePositionCounter);
2442     if (!theXCAFModifiers.IsEmpty())
2443       aDatObj->SetModifiers(theXCAFModifiers);
2444     if (theXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None)
2445       aDatObj->SetModifierWithValue(theXCAFModifWithVal, theModifValue);
2446     aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2447     if (aDatObj->GetPresentation().IsNull()) {
2448       // Try find annotation connected to datum entity (not right case, according recommended practices)
2449       readAnnotation(aTR, theDat, aDatObj);
2450     }
2451     aDat->SetObject(aDatObj);
2452   }
2453
2454   return Standard_True;
2455 }
2456
2457
2458 //=======================================================================
2459 //function : ReadDatums
2460 //purpose  : auxilary
2461 //=======================================================================
2462 Standard_Boolean STEPCAFControl_Reader::readDatumsAP242(const Handle(Standard_Transient)& theEnt,
2463   const TDF_Label theGDTL,
2464   const Handle(TDocStd_Document)& theDoc,
2465   const Handle(XSControl_WorkSession)& theWS)
2466 {
2467   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2468   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2469   const Interface_Graph& aGraph = aTP->Graph();
2470
2471   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2472   for (anIter.Start(); anIter.More(); anIter.Next()) {
2473     Handle(Standard_Transient) anAtr = anIter.Value();
2474     if (anAtr->IsKind(STANDARD_TYPE(StepDimTol_DatumSystem)))
2475     {
2476       Standard_Integer aPositionCounter = 0;//position on frame 
2477       Handle(StepDimTol_DatumSystem) aDS = Handle(StepDimTol_DatumSystem)::DownCast(anAtr);
2478       Interface_EntityIterator anIterDS = aGraph.Sharings(aDS);
2479       for (anIterDS.Start(); anIterDS.More(); anIterDS.Next()) {
2480         Handle(Standard_Transient) anAtrDS = anIterDS.Value();
2481         if (anAtrDS->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2482         {
2483           //get axis
2484           Handle(StepAP242_GeometricItemSpecificUsage)aAxGISUI
2485             = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anAtrDS);
2486           if (aAxGISUI->IdentifiedItemValue(1)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2487           {
2488             Handle(StepGeom_Axis2Placement3d) anAx
2489               = Handle(StepGeom_Axis2Placement3d)::DownCast(aAxGISUI->IdentifiedItemValue(1));
2490             Handle(XCAFDoc_GeomTolerance) aTol;
2491             if (theGDTL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aTol))
2492             {
2493               Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aTol->GetObject();
2494               Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2495               Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2496               Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2497               gp_Dir aDir;
2498               gp_Dir aDirR;
2499               gp_Pnt aPnt;
2500               if (!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2501                 !aDirRArr.IsNull() && aDirRArr->Length() > 2 &&
2502                 !aLocArr.IsNull() && aLocArr->Length() > 2)
2503               {
2504                 aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower() + 1, aDirArr->Lower() + 2);
2505                 aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower() + 1, aDirRArr->Lower() + 2);
2506                 aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower() + 1, aLocArr->Lower() + 2);
2507                 gp_Ax2 anA(aPnt, aDir, aDirR);
2508                 anObj->SetAxis(anA);
2509                 aTol->SetObject(anObj);
2510               }
2511             }
2512           }
2513         }
2514       }
2515       if (aDS->NbConstituents() > 0)
2516       {
2517         //get datum feature and datum target from datum system
2518         Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aDRCA = aDS->Constituents();
2519         if (!aDRCA.IsNull())
2520         {
2521           for (Standard_Integer i = aDRCA->Lower(); i <= aDRCA->Upper(); i++)
2522           {
2523             Handle(StepDimTol_DatumReferenceCompartment) aDRC = aDRCA->Value(i);
2524             //gete modifiers
2525             Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModif = aDRC->Modifiers();
2526             XCAFDimTolObjects_DatumModifiersSequence aXCAFModifiers;
2527             XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal = XCAFDimTolObjects_DatumModifWithValue_None;
2528             Standard_Real aModifValue = 0;
2529             if (!aModif.IsNull())
2530             {
2531               for (Standard_Integer m = aModif->Lower(); m <= aModif->Upper(); m++)
2532               {
2533                 if (aModif->Value(m).CaseNumber() == 2)
2534                   aXCAFModifiers.Append(
2535                   (XCAFDimTolObjects_DatumSingleModif)aModif->Value(m).
2536                     SimpleDatumReferenceModifierMember()->Value());
2537                 else if (aModif->Value(m).CaseNumber() == 1)
2538                 {
2539                   aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModif->Value(m).DatumReferenceModifierWithValue()->ModifierType() + 1);
2540                   Standard_Real aVal = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2541                   StepBasic_Unit anUnit = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2542                   if (anUnit.IsNull()) continue;
2543                   if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2544                   Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2545                   STEPConstruct_UnitContext anUnitCtx;
2546                   anUnitCtx.ComputeFactors(NU);
2547                   aModifValue = aVal * anUnitCtx.LengthFactor();
2548                 }
2549               }
2550             }
2551             aPositionCounter++;
2552             Interface_EntityIterator anIterDRC = aGraph.Shareds(aDRC);
2553             for (anIterDRC.Start(); anIterDRC.More(); anIterDRC.Next()) {
2554
2555               if (anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2556               {
2557                 Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRC.Value());
2558                 setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue, theDoc, theWS);
2559               }
2560               else if (anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_DatumReferenceElement)))
2561               {
2562                 Handle(StepDimTol_DatumReferenceElement) aDRE
2563                   = Handle(StepDimTol_DatumReferenceElement)::DownCast(anIterDRC.Value());
2564                 //get modifiers from group of datums
2565                 Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifE = aDRE->Modifiers();
2566                 if (!aModifE.IsNull())
2567                 {
2568                   for (Standard_Integer k = aModifE->Lower(); k <= aModifE->Upper(); k++)
2569                   {
2570                     if (aModifE->Value(k).CaseNumber() == 2)
2571                       aXCAFModifiers.Append(
2572                       (XCAFDimTolObjects_DatumSingleModif)aModifE->Value(k).
2573                         SimpleDatumReferenceModifierMember()->Value());
2574                     else if (aModifE->Value(k).CaseNumber() == 1)
2575                     {
2576                       aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierType() + 1);
2577                       Standard_Real aVal = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2578                       StepBasic_Unit anUnit = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2579                       if (anUnit.IsNull()) continue;
2580                       if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2581                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2582                       STEPConstruct_UnitContext anUnitCtx;
2583                       anUnitCtx.ComputeFactors(NU);
2584                       aModifValue = aVal * anUnitCtx.LengthFactor();
2585                     }
2586                   }
2587                 }
2588                 Interface_EntityIterator anIterDRE = aGraph.Shareds(aDRE);
2589                 for (anIterDRE.Start(); anIterDRE.More(); anIterDRE.Next()) {
2590                   if (anIterDRE.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2591                   {
2592                     Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRE.Value());
2593                     setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue, theDoc, theWS);
2594                   }
2595                 }
2596               }
2597             }
2598           }
2599         }
2600       }
2601     }
2602   }
2603   return Standard_True;
2604 }
2605
2606 //=======================================================================
2607 //function : createGeomTolObjectInXCAF
2608 //purpose  : 
2609 //=======================================================================
2610 TDF_Label STEPCAFControl_Reader::createGDTObjectInXCAF(const Handle(Standard_Transient)& theEnt,
2611   const Handle(TDocStd_Document)& theDoc,
2612   const Handle(XSControl_WorkSession)& theWS)
2613 {
2614   TDF_Label aGDTL;
2615   if (!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2616     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) &&
2617     !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2618   {
2619     return aGDTL;
2620   }
2621
2622   Handle(TCollection_HAsciiString) aSemanticName;
2623
2624   // protection against invalid input
2625   if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2626     Handle(StepDimTol_GeometricTolerance) aGeomTol = Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2627     if (aGeomTol->TolerancedShapeAspect().IsNull())
2628       return aGDTL;
2629     aSemanticName = aGeomTol->Name();
2630   }
2631   if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2632     Handle(StepShape_DimensionalSize) aDim = Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2633     if (aDim->AppliesTo().IsNull())
2634       return aGDTL;
2635     aSemanticName = aDim->Name();
2636   }
2637   if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2638     Handle(StepShape_DimensionalLocation) aDim = Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
2639     if (aDim->RelatedShapeAspect().IsNull() || aDim->RelatingShapeAspect().IsNull())
2640       return aGDTL;
2641     aSemanticName = aDim->Name();
2642   }
2643
2644   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
2645   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
2646   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2647   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2648   const Interface_Graph& aGraph = aTP->Graph();
2649   Standard_Boolean isAllAround = Standard_False;
2650   Standard_Boolean isAllOver = Standard_False;
2651
2652   // find RepresentationItem for current Ent
2653   NCollection_Sequence<Handle(Standard_Transient)> aSeqRI1, aSeqRI2;
2654
2655   // Collect all Shape_Aspect entities
2656   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2657   for (anIter.Start(); anIter.More(); anIter.Next()) {
2658     Handle(Standard_Transient) anAtr = anIter.Value();
2659     NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2660     if (anAtr->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)))
2661     {
2662       //if associating tolerances with part (All-Over)
2663       Interface_EntityIterator anIterSDR = aGraph.Sharings(anAtr);
2664       for (anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next())
2665       {
2666         Handle(Standard_Transient) anAtrSDR = anIterSDR.Value();
2667         if (anAtrSDR->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2668         {
2669           isAllOver = Standard_True;
2670           Interface_EntityIterator anIterABSR = aGraph.Shareds(anAtrSDR);
2671           for (anIterABSR.Start(); anIterABSR.More(); anIterABSR.Next())
2672           {
2673             Handle(Standard_Transient) anAtrABSR = anIterABSR.Value();
2674             if (anAtrABSR->IsKind(STANDARD_TYPE(StepShape_AdvancedBrepShapeRepresentation)))
2675             {
2676               aSeqRI1.Append(anAtrABSR);
2677             }
2678           }
2679         }
2680       }
2681     }
2682     else if (anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
2683       anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2684     {
2685       //if tolerance attached to dimension
2686       Interface_EntityIterator anIterDim = aGraph.Shareds(anAtr);
2687       for (anIterDim.Start(); anIterDim.More(); anIterDim.Next())
2688       {
2689         Handle(StepRepr_ShapeAspect) aSA = Handle(StepRepr_ShapeAspect)::DownCast(anIterDim.Value());
2690         if (!aSA.IsNull()) {
2691           collectShapeAspect(aSA, theWS, aSAs);
2692         }
2693       }
2694     }
2695     else if (anAtr->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2696     {
2697       if (anAtr->IsKind(STANDARD_TYPE(StepRepr_AllAroundShapeAspect)))
2698       {
2699         // if applyed AllAround Modifier
2700         isAllAround = Standard_True;
2701       }
2702       // dimensions and default tolerances
2703       Handle(StepRepr_ShapeAspect) aSA = Handle(StepRepr_ShapeAspect)::DownCast(anAtr);
2704       if (!aSA.IsNull()) {
2705         collectShapeAspect(aSA, theWS, aSAs);
2706       }
2707     }
2708
2709     // Collect all representation items
2710     if (!aSAs.IsEmpty())
2711     {
2712       //get representation items
2713       NCollection_Sequence<Handle(Standard_Transient)> aSeqRI;
2714       for (Standard_Integer i = aSAs.Lower(); i <= aSAs.Upper(); i++)
2715       {
2716         Interface_EntityIterator anIterSA = aGraph.Sharings(aSAs.Value(i));
2717         Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2718         Handle(StepRepr_PropertyDefinition) PropD;
2719         for (anIterSA.Start(); anIterSA.More() && aGISU.IsNull() && PropD.IsNull(); anIterSA.Next()) {
2720           aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2721           PropD = Handle(StepRepr_PropertyDefinition)::DownCast(anIterSA.Value());
2722         }
2723         if (!PropD.IsNull())//for old version
2724         {
2725           Handle(StepRepr_RepresentationItem) RI;
2726           Interface_EntityIterator subs4 = aGraph.Sharings(PropD);
2727           for (subs4.Start(); subs4.More(); subs4.Next()) {
2728             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
2729               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
2730             if (!SDR.IsNull()) {
2731               Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2732               if (!Repr.IsNull() && Repr->NbItems() > 0) {
2733                 RI = Repr->ItemsValue(1);
2734               }
2735             }
2736           }
2737           if (RI.IsNull()) continue;
2738
2739           if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2740             // read dimensions
2741             Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
2742             if (EC.IsNull()) continue;
2743             Handle(TCollection_HAsciiString) aName;
2744             Handle(StepShape_DimensionalSize) DimSize =
2745               Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2746             Standard_Real dim1 = -1., dim2 = -1.;
2747             subs4 = aGraph.Sharings(DimSize);
2748             for (subs4.Start(); subs4.More(); subs4.Next()) {
2749               Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR =
2750                 Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
2751               if (!DimCharR.IsNull()) {
2752                 Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
2753                 if (!SDimR.IsNull() && SDimR->NbItems() > 0) {
2754                   Handle(StepRepr_RepresentationItem) anItem = SDimR->ItemsValue(1);
2755                   Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(anItem);
2756                   if (!VR.IsNull()) {
2757                     aName = VR->Name();
2758                     //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
2759                     //if(CID.IsNull()) continue;
2760                     //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
2761                     //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
2762                     //if(CIDM.IsNull()) continue;
2763                     //if(CIDM->ArrTransient().IsNull()) continue;
2764                     //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
2765                     //if(CID.CaseMem(CIDM)==1)
2766                     //  HARI = CID.ListRepresentationItem();
2767                     //if(CID.CaseMem(CIDM)==2)
2768                     //  HARI = CID.SetRepresentationItem();
2769                     Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
2770                     if (HARI.IsNull()) continue;
2771                     if (HARI->Length() > 0) {
2772                       Handle(StepRepr_RepresentationItem) RI1 = HARI->Value(1);
2773                       if (RI1.IsNull()) continue;
2774                       if (RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2775                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2776                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
2777                         dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2778                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2779                         if (anUnit.IsNull()) continue;
2780                         if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2781                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2782                         STEPConstruct_UnitContext anUnitCtx;
2783                         anUnitCtx.ComputeFactors(NU);
2784                         dim1 = dim1 * anUnitCtx.LengthFactor();
2785                       }
2786                     }
2787                     if (HARI->Length() > 1) {
2788                       Handle(StepRepr_RepresentationItem) RI2 = HARI->Value(2);
2789                       if (RI2.IsNull()) continue;
2790                       if (RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2791                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2792                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
2793                         dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2794                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2795                         if (anUnit.IsNull()) continue;
2796                         if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2797                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2798                         STEPConstruct_UnitContext anUnitCtx;
2799                         anUnitCtx.ComputeFactors(NU);
2800                         dim2 = dim2 * anUnitCtx.LengthFactor();
2801                       }
2802                     }
2803                   }
2804                 }
2805               }
2806             }
2807             if (dim1 < 0) continue;
2808             if (dim2 < 0) dim2 = dim1;
2809             //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
2810             // now we know edge_curve and value range therefore
2811             // we can create corresponding D&GT labels
2812             Standard_Integer index = aTP->MapIndex(EC);
2813             TopoDS_Shape aSh;
2814             if (index > 0) {
2815               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2816               aSh = TransferBRep::ShapeResult(binder);
2817             }
2818             if (aSh.IsNull()) continue;
2819             TDF_Label shL;
2820             if (!aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True)) continue;
2821             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1, 2);
2822             arr->SetValue(1, dim1);
2823             arr->SetValue(2, dim2);
2824             aDGTTool->SetDimTol(shL, 1, arr, aName, DimSize->Name());
2825           }
2826           // read tolerances and datums
2827           else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2828             Handle(StepDimTol_GeometricTolerance) GT =
2829               Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2830             // read common data for tolerance
2831             //Standard_Real dim = GT->Magnitude()->ValueComponent();
2832             Handle(StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
2833             if (dim3.IsNull()) continue;
2834             Standard_Real dim = dim3->ValueComponent();
2835             StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
2836             if (anUnit.IsNull()) continue;
2837             if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
2838             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2839             STEPConstruct_UnitContext anUnitCtx;
2840             anUnitCtx.ComputeFactors(NU);
2841             dim = dim * anUnitCtx.LengthFactor();
2842             //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
2843             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1, 1);
2844             arr->SetValue(1, dim);
2845             Handle(TCollection_HAsciiString) aName = GT->Name();
2846             Handle(TCollection_HAsciiString) aDescription = GT->Description();
2847             Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2848             if (AF.IsNull()) continue;
2849             Standard_Integer index = aTP->MapIndex(AF);
2850             TopoDS_Shape aSh;
2851             if (index > 0) {
2852               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2853               aSh = TransferBRep::ShapeResult(binder);
2854             }
2855             if (aSh.IsNull()) continue;
2856             TDF_Label shL;
2857             if (!aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True)) continue;
2858             // read specific data for tolerance
2859             if (GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
2860               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2861                 Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(theEnt);
2862               Standard_Integer kind = 20;
2863               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2864                 GTComplex->GetModifiedGeometricTolerance();
2865               if (!MGT.IsNull()) {
2866                 kind = kind + MGT->Modifier() + 1;
2867               }
2868               TDF_Label TolerL = aDGTTool->SetDimTol(shL, kind, arr, aName, aDescription);
2869               // translate datums connected with this tolerance
2870               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2871                 GTComplex->GetGeometricToleranceWithDatumReference();
2872               if (!GTWDR.IsNull()) {
2873                 ReadDatums(aSTool, aDGTTool, aGraph, aTP, TolerL, GTWDR);
2874               }
2875             }
2876             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
2877               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2878                 Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(theEnt);
2879               if (GTWDR.IsNull()) continue;
2880               Standard_Integer kind = 0;
2881               if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
2882               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
2883               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
2884               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
2885               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
2886               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
2887               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
2888               else if (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
2889               //cout<<"GTWDR: kind="<<kind<<endl;
2890               TDF_Label TolerL = aDGTTool->SetDimTol(shL, kind, arr, aName, aDescription);
2891               ReadDatums(aSTool, aDGTTool, aGraph, aTP, TolerL, GTWDR);
2892             }
2893             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
2894               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2895                 Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(theEnt);
2896               Standard_Integer kind = 35 + MGT->Modifier();
2897               aDGTTool->SetDimTol(shL, kind, arr, aName, aDescription);
2898             }
2899             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
2900               aDGTTool->SetDimTol(shL, 38, arr, aName, aDescription);
2901             }
2902             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
2903               aDGTTool->SetDimTol(shL, 39, arr, aName, aDescription);
2904             }
2905             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
2906               aDGTTool->SetDimTol(shL, 40, arr, aName, aDescription);
2907             }
2908             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
2909               aDGTTool->SetDimTol(shL, 41, arr, aName, aDescription);
2910             }
2911             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
2912               aDGTTool->SetDimTol(shL, 42, arr, aName, aDescription);
2913             }
2914             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
2915               aDGTTool->SetDimTol(shL, 43, arr, aName, aDescription);
2916             }
2917             else if (GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
2918               aDGTTool->SetDimTol(shL, 44, arr, aName, aDescription);
2919             }
2920           }
2921         }
2922         else
2923         {
2924           if (aGISU.IsNull()) continue;
2925           Standard_Integer j = 1;
2926           for (; j <= aGISU->NbIdentifiedItem(); j++) {
2927             aSeqRI.Append(aGISU->IdentifiedItemValue(j));
2928           }
2929         }
2930       }
2931       if (!aSeqRI.IsEmpty())
2932       {
2933         if (aSeqRI1.IsEmpty())
2934           aSeqRI1 = aSeqRI;
2935         else
2936           aSeqRI2 = aSeqRI;
2937       }
2938     }
2939   }
2940   if (aSeqRI1.IsEmpty())
2941     return aGDTL;
2942
2943   TDF_LabelSequence aShLS1, aShLS2;
2944
2945   // Collect shapes
2946   for (Standard_Integer i = aSeqRI1.Lower(); i <= aSeqRI1.Upper();i++)
2947   {
2948     Standard_Integer anIndex = FindShapeIndexForDGT(aSeqRI1.Value(i), theWS);
2949     TopoDS_Shape aSh;
2950     if (anIndex > 0) {
2951       Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2952       aSh = TransferBRep::ShapeResult(aBinder);
2953     }
2954     if (!aSh.IsNull())
2955     {
2956       TDF_Label aShL;
2957       aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2958       if (aShL.IsNull() && aSh.ShapeType() == TopAbs_WIRE)
2959       {
2960         TopExp_Explorer ex(aSh, TopAbs_EDGE, TopAbs_SHAPE);
2961         while (ex.More())
2962         {
2963           TDF_Label edgeL;
2964           aSTool->Search(ex.Current(), edgeL, Standard_True, Standard_True, Standard_True);
2965           if (!edgeL.IsNull())
2966             aShLS1.Append(edgeL);
2967           ex.Next();
2968         }
2969       }
2970       if (!aShL.IsNull())
2971         aShLS1.Append(aShL);
2972     }
2973   }
2974   if (!aSeqRI2.IsEmpty())
2975   {
2976     //for dimensional location
2977     for (Standard_Integer i = aSeqRI2.Lower(); i <= aSeqRI2.Upper();i++)
2978     {
2979       Standard_Integer anIndex = FindShapeIndexForDGT(aSeqRI2.Value(i), theWS);
2980       TopoDS_Shape aSh;
2981       if (anIndex > 0) {
2982         Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2983         aSh = TransferBRep::ShapeResult(aBinder);
2984       }
2985       if (!aSh.IsNull())
2986       {
2987         TDF_Label aShL;
2988         aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2989         if (aShL.IsNull() && aSh.ShapeType() == TopAbs_WIRE)
2990         {
2991           TopExp_Explorer ex(aSh, TopAbs_EDGE, TopAbs_SHAPE);
2992           while (ex.More())
2993           {
2994             TDF_Label edgeL;
2995             aSTool->Search(ex.Current(), edgeL, Standard_True, Standard_True, Standard_True);
2996             if (!edgeL.IsNull())
2997               aShLS2.Append(edgeL);
2998             ex.Next();
2999           }
3000         }
3001         if (!aShL.IsNull())
3002           aShLS2.Append(aShL);
3003       }
3004     }
3005   }
3006
3007   if (!aShLS1.IsEmpty())
3008   {
3009     // add to XCAF
3010     if (!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
3011     {
3012       aGDTL = aDGTTool->AddDimension();
3013       myGDTMap.Bind(theEnt, aGDTL);
3014       aDGTTool->Lock(aGDTL);
3015       Handle(XCAFDoc_Dimension) aDim = XCAFDoc_Dimension::Set(aGDTL);
3016       TCollection_AsciiString aStr("DGT:Dimensional_");
3017       if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
3018       {
3019         aStr.AssignCat("Size");
3020       }
3021       else if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
3022       {
3023         aStr.AssignCat("Location");
3024       }
3025       TDataStd_Name::Set(aGDTL, aStr);
3026
3027       if (!aShLS2.IsEmpty())
3028       {
3029         aDGTTool->SetDimension(aShLS1, aShLS2, aGDTL);
3030       }
3031       else
3032       {
3033         TDF_LabelSequence aEmptySeq;
3034         aDGTTool->SetDimension(aShLS1, aEmptySeq, aGDTL);
3035       }
3036     }
3037     else
3038     {
3039       aGDTL = aDGTTool->AddGeomTolerance();
3040       myGDTMap.Bind(theEnt, aGDTL);
3041       aDGTTool->Lock(aGDTL);
3042       Handle(XCAFDoc_GeomTolerance) aGTol = XCAFDoc_GeomTolerance::Set(aGDTL);
3043       TCollection_AsciiString aStr("DGT:GeomTolerance");
3044       TDataStd_Name::Set(aGDTL, aStr);
3045       aDGTTool->SetGeomTolerance(aShLS1, aGDTL);
3046       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aGTol->GetObject();
3047       if (isAllAround)
3048         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Around);
3049       else if (isAllOver)
3050         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Over);
3051       aGTol->SetObject(anObj);
3052     }
3053
3054     if (aSemanticName)
3055     {
3056       TCollection_ExtendedString str(aSemanticName->String());
3057       TDataStd_Name::Set(aGDTL, str);
3058     }
3059
3060     readDatumsAP242(theEnt, aGDTL, theDoc, theWS);
3061   }
3062   return aGDTL;
3063 }
3064
3065 //=======================================================================
3066 //function : convertAngleValue
3067 //purpose  : auxilary
3068 //=======================================================================
3069 void convertAngleValue(
3070   const STEPConstruct_UnitContext& anUnitCtx,
3071   Standard_Real& aVal)
3072 {
3073   // convert radian to deg
3074   Standard_Real aFact = anUnitCtx.PlaneAngleFactor() * 180 / M_PI;
3075   // in order to avoid inaccuracy of calculation perform conversion
3076   // only if aFact not eqaul 1 with some precision
3077   if (fabs(1. - aFact) > Precision::Confusion())
3078   {
3079     aVal = aVal * aFact;
3080   }
3081 }
3082
3083
3084 //=======================================================================
3085 //function : setDimObjectToXCAF
3086 //purpose  : 
3087 //=======================================================================
3088 static void setDimObjectToXCAF(const Handle(Standard_Transient)& theEnt,
3089   const TDF_Label& aDimL,
3090   const Handle(TDocStd_Document)& theDoc,
3091   const Handle(XSControl_WorkSession)& theWS)
3092 {
3093   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
3094   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
3095   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
3096   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
3097   const Interface_Graph& aGraph = aTP->Graph();
3098   Handle(XCAFDimTolObjects_DimensionObject) aDimObj;
3099   if (!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
3100     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
3101     return;
3102
3103   Handle(StepShape_DimensionalSize) aDimSize =
3104     Handle(StepShape_DimensionalSize)::DownCast(theEnt);
3105   Handle(StepShape_DimensionalLocation) aDimLocation =
3106     Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
3107
3108   aDimObj = new XCAFDimTolObjects_DimensionObject();
3109   Standard_Real aDim1 = -1., aDim2 = -1., aDim3 = -1.;
3110   Standard_Boolean isPlusMinusTolerance = Standard_False;
3111   Handle(StepShape_TypeQualifier) aTQ;
3112   Handle(StepShape_ValueFormatTypeQualifier) aVFTQ;
3113   Handle(StepShape_ToleranceValue) aTV;
3114   Handle(StepShape_LimitsAndFits) aLAF;
3115   Handle(StepRepr_CompoundRepresentationItem) aCRI;
3116   Handle(StepGeom_Axis2Placement3d) anAP;
3117
3118   Interface_EntityIterator anIterDim;
3119   if (!aDimSize.IsNull())
3120   {
3121     anIterDim = aGraph.Sharings(aDimSize);
3122   }
3123   else
3124   {
3125     anIterDim = aGraph.Sharings(aDimLocation);
3126   }
3127   for (anIterDim.Start(); anIterDim.More(); anIterDim.Next()) {
3128     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR =
3129       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anIterDim.Value());
3130     Handle(StepShape_PlusMinusTolerance) aPMT =
3131       Handle(StepShape_PlusMinusTolerance)::DownCast(anIterDim.Value());
3132     if (!aDCR.IsNull()) {
3133       Handle(StepShape_ShapeDimensionRepresentation) aSDR = aDCR->Representation();
3134       if (!aSDR.IsNull()) {
3135         Handle(StepRepr_HArray1OfRepresentationItem) aHARI = aSDR->Items();
3136
3137         if (!aHARI.IsNull())
3138         {
3139           for (Standard_Integer nr = aHARI->Lower(); nr <= aHARI->Upper(); nr++)
3140           {
3141             Handle(StepRepr_RepresentationItem) aDRI = aHARI->Value(nr);
3142             if (aDRI.IsNull()) continue;
3143
3144             if (aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnit))) {
3145               // simple value / range
3146               Handle(StepRepr_ReprItemAndMeasureWithUnit) aMWU =
3147                 Handle(StepRepr_ReprItemAndMeasureWithUnit)::DownCast(aDRI);
3148               Standard_Real aVal = aMWU->GetMeasureWithUnit()->ValueComponent();
3149               StepBasic_Unit anUnit = aMWU->GetMeasureWithUnit()->UnitComponent();
3150               if (anUnit.IsNull())
3151                 continue;
3152               if (!(anUnit.CaseNum(anUnit.Value()) == 1))
3153                 continue;
3154               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3155               STEPConstruct_UnitContext anUnitCtx;
3156               anUnitCtx.ComputeFactors(NU);
3157               if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
3158                 aVal = aVal * anUnitCtx.LengthFactor();
3159
3160               }
3161               else
3162                 if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit))) {
3163                   convertAngleValue(anUnitCtx, aVal);
3164                 }
3165               Handle(TCollection_HAsciiString) aName = aMWU->Name();
3166               if (aName->Search("upper") > 0) // upper limit
3167                 aDim2 = aVal;
3168               else // lower limit or simple nominal value
3169                 aDim1 = aVal;
3170             }
3171             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnitAndQRI))) {
3172               // value with qualifier (minimum/maximum/average)
3173               Handle(StepRepr_ReprItemAndMeasureWithUnitAndQRI) aMWU =
3174                 Handle(StepRepr_ReprItemAndMeasureWithUnitAndQRI)::DownCast(aDRI);
3175               Standard_Real aVal = aMWU->GetMeasureWithUnit()->ValueComponent();
3176               StepBasic_Unit anUnit = aMWU->GetMeasureWithUnit()->UnitComponent();
3177               if (anUnit.IsNull())
3178                 continue;
3179               if (!(anUnit.CaseNum(anUnit.Value()) == 1))
3180                 continue;
3181               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3182               STEPConstruct_UnitContext anUnitCtx;
3183               anUnitCtx.ComputeFactors(NU);
3184               if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI))) {
3185                 aVal = aVal * anUnitCtx.LengthFactor();
3186               }
3187               else
3188                 if (aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI))) {
3189                   convertAngleValue(anUnitCtx, aVal);
3190                 }
3191               Handle(StepShape_QualifiedRepresentationItem) aQRI = aMWU->GetQualifiedRepresentationItem();
3192               if (aQRI->Qualifiers()->Length() == 0) {
3193                 aDim1 = aVal;
3194                 continue;
3195               }
3196               Handle(StepShape_TypeQualifier) aValueType = aQRI->Qualifiers()->Value(1).TypeQualifier();
3197               if (aValueType->Name()->String().IsEqual("minimum"))
3198                 aDim2 = aVal;
3199               else if (aValueType->Name()->String().IsEqual("maximum"))
3200                 aDim3 = aVal;
3201               else aDim1 = aVal;
3202             }
3203             else if (aDRI->IsKind(STANDARD_TYPE(StepShape_QualifiedRepresentationItem))) {
3204               //get qualifier
3205               Handle(StepShape_QualifiedRepresentationItem) aQRI =
3206                 Handle(StepShape_QualifiedRepresentationItem)::DownCast(aDRI);
3207               for (Standard_Integer l = 1; l <= aQRI->NbQualifiers(); l++)
3208               {
3209                 aTQ = aQRI->Qualifiers()->Value(l).TypeQualifier();
3210                 aVFTQ = aQRI->Qualifiers()->Value(l).ValueFormatTypeQualifier();
3211               }
3212             }
3213             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
3214               Handle(StepRepr_DescriptiveRepresentationItem) aDescription =
3215                 Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(aDRI);
3216               aDimObj->AddDescription(aDescription->Description(), aDescription->Name());
3217             }
3218             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_CompoundRepresentationItem))) {
3219               aCRI = Handle(StepRepr_CompoundRepresentationItem)::DownCast(aDRI);
3220             }
3221             else if (aDRI->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
3222             {
3223               anAP = Handle(StepGeom_Axis2Placement3d)::DownCast(aDRI);
3224             }
3225           }
3226         }
3227       }
3228     }
3229     else if (!aPMT.IsNull())
3230     {
3231       isPlusMinusTolerance = Standard_True;
3232       StepShape_ToleranceMethodDefinition aTMD = aPMT->Range();
3233       if (aPMT.IsNull()) continue;
3234       if (aTMD.CaseNumber() == 1)
3235         //! 1 -> ToleranceValue from StepShape
3236         //! 2 -> LimitsAndFits from StepShape
3237       {
3238         //plus minus tolerance 
3239         aTV = aTMD.ToleranceValue();
3240         if (aTV.IsNull()) continue;
3241
3242         Handle(Standard_Transient) aUpperBound = aTV->UpperBound();
3243         if(aUpperBound.IsNull())
3244           continue;
3245         Handle(StepBasic_MeasureWithUnit) aMWU;
3246         if(aUpperBound->IsKind(STANDARD_TYPE(StepBasic_MeasureWithUnit)) )
3247           aMWU = Handle(StepBasic_MeasureWithUnit)::DownCast(aUpperBound);
3248         else if(aUpperBound->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnit)) )
3249         {
3250           Handle(StepRepr_ReprItemAndMeasureWithUnit) aReprMeasureItem = 
3251             Handle(StepRepr_ReprItemAndMeasureWithUnit)::DownCast(aUpperBound);
3252           aMWU = aReprMeasureItem->GetMeasureWithUnit();
3253
3254         }
3255         if(aMWU.IsNull())
3256           continue;
3257         Standard_Real aVal = aMWU->ValueComponent();
3258         StepBasic_Unit anUnit = aMWU->UnitComponent();
3259         if (anUnit.IsNull()) continue;
3260         if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
3261         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3262         STEPConstruct_UnitContext anUnitCtx;
3263         anUnitCtx.ComputeFactors(NU);
3264         if (aMWU->IsKind(STANDARD_TYPE(StepBasic_LengthMeasureWithUnit)) ||
3265           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI)))
3266         {
3267           aVal = aVal * anUnitCtx.LengthFactor();
3268         }
3269         else if (aMWU->IsKind(STANDARD_TYPE(StepBasic_PlaneAngleMeasureWithUnit)) ||
3270           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI)))
3271         {
3272           convertAngleValue(anUnitCtx, aVal);
3273         }
3274         aDim3 = aVal;
3275
3276         
3277         Handle(Standard_Transient) aLowerBound = aTV->LowerBound();
3278         if(aLowerBound.IsNull())
3279           continue;
3280        
3281         if(aLowerBound->IsKind(STANDARD_TYPE(StepBasic_MeasureWithUnit)) )
3282           aMWU = Handle(StepBasic_MeasureWithUnit)::DownCast(aLowerBound);
3283         else if(aLowerBound->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndMeasureWithUnit)) )
3284         {
3285           Handle(StepRepr_ReprItemAndMeasureWithUnit) aReprMeasureItem = 
3286             Handle(StepRepr_ReprItemAndMeasureWithUnit)::DownCast(aLowerBound);
3287           aMWU = aReprMeasureItem->GetMeasureWithUnit();
3288
3289         }
3290         if(aMWU.IsNull())
3291           continue;
3292       
3293         aVal = aMWU->ValueComponent();
3294         anUnit = aMWU->UnitComponent();
3295         if (anUnit.IsNull()) continue;
3296         if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
3297         NU = anUnit.NamedUnit();
3298         anUnitCtx.ComputeFactors(NU);
3299         if (aMWU->IsKind(STANDARD_TYPE(StepBasic_LengthMeasureWithUnit)) ||
3300           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI)))
3301         {
3302           aVal = aVal * anUnitCtx.LengthFactor();
3303         }
3304         else if (aMWU->IsKind(STANDARD_TYPE(StepBasic_PlaneAngleMeasureWithUnit)) ||
3305           aMWU->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI)))
3306         {
3307           convertAngleValue(anUnitCtx, aVal);
3308         }
3309         aDim2 = Abs(aVal);
3310       }
3311       else
3312       {
3313         // class of tolerance
3314         aLAF = aTMD.LimitsAndFits();
3315       }
3316     }
3317   }
3318
3319   if (aDim1 < 0) return;
3320
3321   if (aDim2 < 0)
3322     aDimObj->SetValue(aDim1);
3323   else if (aDim3 < 0)
3324   {
3325     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1, 2);
3326     anArr->SetValue(1, aDim1);
3327     anArr->SetValue(2, aDim2);
3328     aDimObj->SetValues(anArr);
3329   }
3330   else
3331   {
3332     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1, 3);
3333     if (!isPlusMinusTolerance)
3334     {
3335       aDim2 = aDim1 - aDim2;
3336       aDim3 = aDim3 - aDim1;
3337     }
3338     anArr->SetValue(1, aDim1);
3339     anArr->SetValue(2, aDim2);
3340     anArr->SetValue(3, aDim3);
3341     aDimObj->SetValues(anArr);
3342   }
3343   if (!aTQ.IsNull())
3344   {
3345     XCAFDimTolObjects_DimensionQualifier aQ;
3346     if (STEPCAFControl_GDTProperty::GetDimQualifierType(aTQ->Name(), aQ))
3347     {
3348       aDimObj->SetQualifier(aQ);
3349     }
3350   }
3351
3352   if (!aVFTQ.IsNull())
3353   {
3354     //A typical value would be 'NR2 2.2'
3355     TCollection_HAsciiString aFormat = aVFTQ->FormatType();
3356     Standard_Integer i = aFormat.Location(1, ' ', 1, aFormat.Length());
3357     aFormat.SubString(i + 1, i + 1)->IntegerValue();
3358     aDimObj->SetNbOfDecimalPlaces(aFormat.SubString(i + 1, i + 1)->IntegerValue(),
3359       aFormat.SubString(i + 3, i + 3)->IntegerValue());
3360   }
3361
3362   if (!aLAF.IsNull())
3363   {
3364     //get class of tolerance
3365     Standard_Boolean aHolle = Standard_False;
3366     XCAFDimTolObjects_DimensionFormVariance aFV = XCAFDimTolObjects_DimensionFormVariance_None;
3367     XCAFDimTolObjects_DimensionGrade aG = XCAFDimTolObjects_DimensionGrade_IT01;
3368     STEPCAFControl_GDTProperty::GetDimClassOfTolerance(aLAF, aHolle, aFV, aG);
3369     aDimObj->SetClassOfTolerance(aHolle, aFV, aG);
3370   }
3371
3372   if (!aCRI.IsNull() && !aCRI->ItemElement().IsNull() && aCRI->ItemElement()->Length() > 0)
3373   {
3374     //get modifiers
3375     XCAFDimTolObjects_DimensionModifiersSequence aModifiers;
3376     STEPCAFControl_GDTProperty::GetDimModifiers(aCRI, aModifiers);
3377     if (aModifiers.Length() > 0)
3378       aDimObj->SetModifiers(aModifiers);
3379   }
3380
3381   Handle(TCollection_HAsciiString) aName;
3382   if (!aDimSize.IsNull())
3383   {
3384     aName = aDimSize->Name();
3385   }
3386   else
3387   {
3388     aName = aDimLocation->Name();
3389   }
3390   XCAFDimTolObjects_DimensionType aType = XCAFDimTolObjects_DimensionType_Location_None;
3391   if (!STEPCAFControl_GDTProperty::GetDimType(aName, aType))
3392   {
3393     if (!aDimSize.IsNull())
3394     {
3395       Handle(StepShape_AngularSize) anAngSize =
3396         Handle(StepShape_AngularSize)::DownCast(aDimSize);
3397       if (!anAngSize.IsNull())
3398       {
3399         //get qualifier for angular value
3400         aType = XCAFDimTolObjects_DimensionType_Size_Angular;
3401         if (anAngSize->AngleSelection() == StepShape_Equal)
3402           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3403         else if (anAngSize->AngleSelection() == StepShape_Large)
3404           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3405         else if (anAngSize->AngleSelection() == StepShape_Small)
3406           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3407       }
3408     }
3409     else
3410     {
3411       Handle(StepShape_AngularLocation) anAngLoc =
3412         Handle(StepShape_AngularLocation)::DownCast(aDimLocation);
3413       if (!anAngLoc.IsNull())
3414       {
3415         //get qualifier for angular value
3416         aType = XCAFDimTolObjects_DimensionType_Location_Angular;
3417         if (anAngLoc->AngleSelection() == StepShape_Equal)
3418           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3419         else if (anAngLoc->AngleSelection() == StepShape_Large)
3420           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3421         else if (anAngLoc->AngleSelection() == StepShape_Small)
3422           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3423       }
3424     }
3425     if (aType == XCAFDimTolObjects_DimensionType_Location_None)
3426     {
3427       Handle(StepRepr_ShapeAspect) aPSA;
3428       if (!aDimSize.IsNull())
3429       {
3430         Handle(StepShape_DimensionalSizeWithPath) aDimSizeWithPath =
3431           Handle(StepShape_DimensionalSizeWithPath)::DownCast(aDimSize);
3432         if (!aDimSizeWithPath.IsNull())
3433         {
3434           aType = XCAFDimTolObjects_DimensionType_Size_WithPath;
3435           aPSA = aDimSizeWithPath->Path();
3436         }
3437       }
3438       else
3439       {
3440         Handle(StepShape_DimensionalLocationWithPath) aDimLocWithPath =
3441           Handle(StepShape_DimensionalLocationWithPath)::DownCast(aDimLocation);
3442         if (!aDimLocWithPath.IsNull())
3443         {
3444           aType = XCAFDimTolObjects_DimensionType_Location_WithPath;
3445           aPSA = aDimLocWithPath->Path();
3446         }
3447       }
3448
3449       if (!aPSA.IsNull())
3450       {
3451         //for DimensionalLocationWithPath
3452         Handle(StepGeom_GeometricRepresentationItem) aGRI;
3453         Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
3454         Interface_EntityIterator anIterDSWP = aGraph.Sharings(aPSA);
3455         for (anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
3456           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
3457         }
3458         if (aPGISU.IsNull()) return;
3459         if (aPGISU->NbIdentifiedItem() > 0) {
3460           aGRI = Handle(StepGeom_GeometricRepresentationItem)::DownCast(aPGISU->IdentifiedItemValue(1));
3461         }
3462         if (aGRI.IsNull()) return;
3463         Handle(StepRepr_RepresentationItem) aPRI;
3464         Interface_EntityIterator anIterGRI = aGraph.Sharings(aGRI);
3465         for (anIterGRI.Start(); anIterGRI.More() && aPGISU.IsNull(); anIterGRI.Next()) {
3466           aPRI = Handle(StepRepr_RepresentationItem)::DownCast(anIterGRI.Value());
3467         }
3468         Standard_Integer anIndex = FindShapeIndexForDGT(aPRI, theWS);
3469         TopoDS_Edge aSh;
3470         if (anIndex > 0) {
3471           Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
3472           aSh = TopoDS::Edge(TransferBRep::ShapeResult(aBinder));
3473         }
3474         if (aSh.IsNull()) return;
3475         aDimObj->SetPath(aSh);
3476       }
3477       else if (!anAP.IsNull())
3478       {
3479         if (anAP->Name()->String().IsEqual("orientation") && !anAP->Axis().IsNull())
3480         {
3481           //for Oriented Dimensional Location
3482           Handle(TColStd_HArray1OfReal) aDirArr = anAP->RefDirection()->DirectionRatios();
3483           gp_Dir aDir;
3484           if (!aDirArr.IsNull() && aDirArr->Length() > 2)
3485           {
3486             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower() + 1, aDirArr->Lower() + 2);
3487             aDimObj->SetDirection(aDir);
3488           }
3489           else if (aDirArr->Length() > 1)
3490           {
3491             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower() + 1, 0);
3492             aDimObj->SetDirection(aDir);
3493           }
3494         }
3495       }
3496     }
3497   }
3498   aDimObj->SetType(aType);
3499
3500
3501   if (!aDimObj.IsNull())
3502   {
3503
3504     Handle(XCAFDoc_Dimension) aDim;
3505
3506     if (aDimL.FindAttribute(XCAFDoc_Dimension::GetID(), aDim))
3507     {
3508       readAnnotation(aTR, theEnt, aDimObj);
3509       readConnectionPoints(aTR, theEnt, aDimObj);
3510       aDim->SetObject(aDimObj);
3511     }
3512   }
3513 }
3514
3515 //=======================================================================
3516 //function : getTolType
3517 //purpose  : 
3518 //=======================================================================
3519 static Standard_Boolean getTolType(const Handle(Standard_Transient)& theEnt,
3520   XCAFDimTolObjects_GeomToleranceType& theType)
3521 {
3522   if (theEnt.IsNull() || !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
3523     return Standard_False;
3524   theType = XCAFDimTolObjects_GeomToleranceType_None;
3525   if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRef)))
3526   {
3527     Handle(StepDimTol_GeoTolAndGeoTolWthDatRef) anE = Handle(StepDimTol_GeoTolAndGeoTolWthDatRef)::DownCast(theEnt);
3528     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3529   }
3530   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3531   {
3532     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) anE =
3533       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)::DownCast(theEnt);
3534     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3535   }
3536   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)))
3537   {
3538     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod) anE =
3539       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)::DownCast(theEnt);
3540     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3541   }
3542   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3543   {
3544     Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) anE =
3545       Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)::DownCast(theEnt);
3546     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3547   }
3548   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMod)))
3549   {
3550     Handle(StepDimTol_GeoTolAndGeoTolWthMod) anE =
3551       Handle(StepDimTol_GeoTolAndGeoTolWthMod)::DownCast(theEnt);
3552     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3553   }
3554   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol)))
3555   {
3556     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol) anE =
3557       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol)::DownCast(theEnt);
3558     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3559   }
3560   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))
3561   {
3562     theType = XCAFDimTolObjects_GeomToleranceType_Angularity;
3563   }
3564   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))
3565   {
3566     theType = XCAFDimTolObjects_GeomToleranceType_CircularRunout;
3567   }
3568   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance)))
3569   {
3570     theType = XCAFDimTolObjects_GeomToleranceType_CircularityOrRoundness;
3571   }
3572   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))
3573   {
3574     theType = XCAFDimTolObjects_GeomToleranceType_Coaxiality;
3575   }
3576   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))
3577   {
3578     theType = XCAFDimTolObjects_GeomToleranceType_Concentricity;
3579   }
3580   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance)))
3581   {
3582     theType = XCAFDimTolObjects_GeomToleranceType_Cylindricity;
3583   }
3584   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance)))
3585   {
3586     theType = XCAFDimTolObjects_GeomToleranceType_Flatness;
3587   }
3588   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))
3589   {
3590     theType = XCAFDimTolObjects_GeomToleranceType_Parallelism;
3591   }
3592   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance)))
3593   {
3594     theType = XCAFDimTolObjects_GeomToleranceType_Perpendicularity;
3595   }
3596   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance)) ||
3597     theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)))
3598   {
3599     theType = XCAFDimTolObjects_GeomToleranceType_Position;
3600   }
3601   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance)))
3602   {
3603     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfLine;
3604   }
3605   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance)))
3606   {
3607     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfSurface;
3608   }
3609   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance)))
3610   {
3611     theType = XCAFDimTolObjects_GeomToleranceType_Straightness;
3612   }
3613   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))
3614   {
3615     theType = XCAFDimTolObjects_GeomToleranceType_Symmetry;
3616   }
3617   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))
3618   {
3619     theType = XCAFDimTolObjects_GeomToleranceType_TotalRunout;
3620   }
3621   return Standard_True;
3622 }
3623 //=======================================================================
3624 //function : setGeomTolObjectToXCAF
3625 //purpose  : 
3626 //=======================================================================
3627 static void setGeomTolObjectToXCAF(const Handle(Standard_Transient)& theEnt,
3628   const TDF_Label& theTolL,
3629   const Handle(TDocStd_Document)& theDoc,
3630   const Handle(XSControl_WorkSession)& theWS)
3631 {
3632   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
3633   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
3634   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
3635   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
3636   const Interface_Graph& aGraph = aTP->Graph();
3637   Handle(XCAFDoc_GeomTolerance) aGTol;
3638   if (!theTolL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aGTol))
3639   {
3640     return;
3641   }
3642   Handle(XCAFDimTolObjects_GeomToleranceObject) aTolObj = aGTol->GetObject();
3643   Handle(StepDimTol_GeometricTolerance) aTolEnt = Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
3644
3645   XCAFDimTolObjects_GeomToleranceType aType = XCAFDimTolObjects_GeomToleranceType_None;
3646   getTolType(theEnt, aType);
3647   aTolObj->SetType(aType);
3648   if (!aTolEnt->Magnitude().IsNull()) {
3649     //get value
3650     Standard_Real aVal = aTolEnt->Magnitude()->ValueComponent();
3651     StepBasic_Unit anUnit = aTolEnt->Magnitude()->UnitComponent();
3652     if (anUnit.IsNull()) return;
3653     if (!(anUnit.CaseNum(anUnit.Value()) == 1)) return;
3654     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3655     STEPConstruct_UnitContext anUnitCtx;
3656     anUnitCtx.ComputeFactors(NU);
3657     aVal = aVal * anUnitCtx.LengthFactor();
3658     aTolObj->SetValue(aVal);
3659   }
3660   //get modifiers
3661   XCAFDimTolObjects_GeomToleranceTypeValue aTypeV = XCAFDimTolObjects_GeomToleranceTypeValue_None;
3662   Interface_EntityIterator anIter = aGraph.Sharings(aTolEnt);
3663   for (anIter.Start(); anIter.More(); anIter.Next()) {
3664     if (anIter.Value()->IsKind(STANDARD_TYPE(StepDimTol_ToleranceZone))) {
3665       Handle(StepDimTol_ToleranceZoneForm) aForm
3666         = Handle(StepDimTol_ToleranceZone)::DownCast(anIter.Value())->Form();
3667       STEPCAFControl_GDTProperty::GetTolValueType(aForm->Name(), aTypeV);
3668       Interface_EntityIterator anIt = aGraph.Sharings(anIter.Value());
3669       for (anIt.Start(); anIt.More(); anIt.Next()) {
3670         if (anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_ProjectedZoneDefinition))) {
3671           Handle(StepDimTol_ProjectedZoneDefinition) aPZone
3672             = Handle(StepDimTol_ProjectedZoneDefinition)::DownCast(anIt.Value());
3673           if (!aPZone->ProjectionLength().IsNull())
3674           {
3675             Standard_Real aVal = aPZone->ProjectionLength()->ValueComponent();
3676             StepBasic_Unit anUnit = aPZone->ProjectionLength()->UnitComponent();
3677             if (anUnit.IsNull()) return;
3678             if (!(anUnit.CaseNum(anUnit.Value()) == 1)) return;
3679             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3680             STEPConstruct_UnitContext anUnitCtx;
3681             anUnitCtx.ComputeFactors(NU);
3682             aVal = aVal * anUnitCtx.LengthFactor();
3683             aTolObj->SetValueOfZoneModifier(aVal);
3684             aTolObj->SetZoneModifier(XCAFDimTolObjects_GeomToleranceZoneModif_Projected);
3685           }
3686         }
3687         else if (anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_RunoutZoneDefinition)))
3688         {
3689           Handle(StepDimTol_RunoutZoneDefinition) aRZone
3690             = Handle(StepDimTol_RunoutZoneDefinition)::DownCast(anIt.Value());
3691           if (!aRZone->Orientation().IsNull())
3692           {
3693             Standard_Real aVal = aRZone->Orientation()->Angle()->ValueComponent();
3694             StepBasic_Unit anUnit = aRZone->Orientation()->Angle()->UnitComponent();
3695             if (anUnit.IsNull()) continue;
3696             if (!(anUnit.CaseNum(anUnit.Value()) == 1)) continue;
3697             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3698             STEPConstruct_UnitContext anUnitCtx;
3699             anUnitCtx.ComputeFactors(NU);
3700             convertAngleValue(anUnitCtx, aVal);
3701             aTolObj->SetValueOfZoneModifier(aVal);
3702             aTolObj->SetZoneModifier(XCAFDimTolObjects_GeomToleranceZoneModif_Runout);
3703           }
3704         }
3705       }
3706       aTolObj->SetTypeOfValue(aTypeV);
3707     }
3708   }
3709   Handle(StepDimTol_HArray1OfGeometricToleranceModifier) aModifiers;
3710   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithModifiers)))
3711   {
3712     aModifiers = Handle(StepDimTol_GeometricToleranceWithModifiers)::DownCast(aTolEnt)->Modifiers();
3713   }
3714   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)))
3715   {
3716     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)
3717       ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3718   }
3719   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMod)))
3720   {
3721     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthMod)
3722       ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3723   }
3724   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3725   {
3726     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)
3727       ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3728   }
3729   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3730   {
3731     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)
3732       ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3733   }
3734   if (!aModifiers.IsNull())
3735   {
3736     for (Standard_Integer i = aModifiers->Lower(); i <= aModifiers->Upper(); i++)
3737     {
3738       if (aModifiers->Value(i) == StepDimTol_GTMLeastMaterialRequirement)
3739         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_L);
3740       else if (aModifiers->Value(i) == StepDimTol_GTMMaximumMaterialRequirement)
3741         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_M);
3742       else
3743         aTolObj->AddModifier((XCAFDimTolObjects_GeomToleranceModif)aModifiers->Value(i));
3744     }
3745   }
3746   Standard_Real aVal = 0;
3747   StepBasic_Unit anUnit;
3748   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithMaximumTolerance)))
3749   {
3750     Handle(StepDimTol_GeometricToleranceWithMaximumTolerance) aMax = Handle(StepDimTol_GeometricToleranceWithMaximumTolerance)::DownCast(aTolEnt);
3751     aVal = aMax->MaximumUpperTolerance()->ValueComponent();
3752     anUnit = aMax->MaximumUpperTolerance()->UnitComponent();
3753   }
3754   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3755   {
3756     Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) aMax =
3757       Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)::DownCast(aTolEnt);
3758     aVal = aMax->GetMaxTolerance()->ValueComponent();
3759     anUnit = aMax->GetMaxTolerance()->UnitComponent();
3760   }
3761   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3762   {
3763     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) aMax =
3764       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)::DownCast(aTolEnt);
3765     aVal = aMax->GetMaxTolerance()->ValueComponent();
3766     anUnit = aMax->GetMaxTolerance()->UnitComponent();
3767   }
3768   if (!anUnit.IsNull() && (anUnit.CaseNum(anUnit.Value()) == 1))
3769   {
3770     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3771     STEPConstruct_UnitContext anUnitCtx;
3772     anUnitCtx.ComputeFactors(NU);
3773     convertAngleValue(anUnitCtx, aVal);
3774     aTolObj->SetMaxValueModifier(aVal);
3775   }
3776
3777   readAnnotation(aTR, theEnt, aTolObj);
3778   aGTol->SetObject(aTolObj);
3779 }
3780
3781 //=======================================================================
3782 //function : ReadGDTs
3783 //purpose  : 
3784 //=======================================================================
3785
3786 Standard_Boolean STEPCAFControl_Reader::ReadGDTs(const Handle(XSControl_WorkSession)& theWS,
3787   Handle(TDocStd_Document)& theDoc)
3788 {
3789   const Handle(Interface_InterfaceModel) &aModel = theWS->Model();
3790   const Interface_Graph& aGraph = theWS->Graph();
3791   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
3792   Handle(StepData_StepModel) aSM = Handle(StepData_StepModel)::DownCast(aModel);
3793   Interface_EntityIterator anI = aSM->Header();
3794   Handle(HeaderSection_FileSchema) aH;
3795   for (anI.Start(); anI.More() && aH.IsNull();anI.Next())
3796     aH = Handle(HeaderSection_FileSchema)::DownCast(anI.Value());
3797   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool(theDoc->Main());
3798   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool(theDoc->Main());
3799   if (aDGTTool.IsNull()) return Standard_False;
3800
3801   Standard_Integer nb = aModel->NbEntities();
3802   for (Standard_Integer i = 1; i <= nb; i++) {
3803     Handle(Standard_Transient) anEnt = aModel->Value(i);
3804     if (anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) ||
3805       anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
3806       anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3807       TDF_Label aGDTL = createGDTObjectInXCAF(anEnt, theDoc, theWS);
3808       if (!aGDTL.IsNull()) {
3809         if (anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3810           setGeomTolObjectToXCAF(anEnt, aGDTL, theDoc, theWS);
3811         }
3812         else {
3813           setDimObjectToXCAF(anEnt, aGDTL, theDoc, theWS);
3814         }
3815       }
3816     }
3817     else if (anEnt->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout)) ||
3818       anEnt->IsKind(STANDARD_TYPE(StepVisual_AnnotationOccurrence)))
3819     {
3820       // Protection against import presentation twice
3821       Handle(StepVisual_DraughtingCallout) aDC;
3822       for (Interface_EntityIterator anIter = aGraph.Sharings(anEnt); anIter.More() && aDC.IsNull(); anIter.Next()) {
3823         aDC = Handle(StepVisual_DraughtingCallout)::DownCast(anIter.Value());
3824       }
3825       if (!aDC.IsNull())
3826         continue;
3827       // Read presentations for PMIs without semantic data.
3828       Handle(StepAP242_DraughtingModelItemAssociation) aDMIA;
3829       TDF_LabelSequence aShapesL;
3830       for (Interface_EntityIterator anIter = aGraph.Sharings(anEnt); anIter.More() && aDMIA.IsNull(); anIter.Next()) {
3831         aDMIA = Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(anIter.Value());
3832       }
3833       if (!aDMIA.IsNull()) {
3834         // Check entity, skip all, attached to GDTs
3835         Handle(StepRepr_ShapeAspect) aDefinition = aDMIA->Definition().ShapeAspect();
3836         if (!aDefinition.IsNull()) {
3837           Standard_Boolean isConnectedToGDT = Standard_False;
3838           // Skip if definition is a datum
3839           if (aDefinition->IsKind(STANDARD_TYPE(StepDimTol_Datum)) ||
3840             aDefinition->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)) ||
3841             aDefinition->IsKind(STANDARD_TYPE(StepDimTol_DatumFeature)) ||
3842             aDefinition->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp))) {
3843             isConnectedToGDT = Standard_True;
3844           }
3845           // Skip if any GDT is applied to definition
3846           for (Interface_EntityIterator anIter = aGraph.Sharings(aDefinition); anIter.More() && !isConnectedToGDT; anIter.Next()) {
3847             if (anIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) ||
3848               anIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
3849               anIter.Value()->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3850               isConnectedToGDT = Standard_True;
3851               continue;
3852             }
3853             Handle(StepRepr_ShapeAspectRelationship) aSAR = Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIter.Value());
3854             if (!aSAR.IsNull()) {
3855               Handle(StepRepr_ShapeAspect) aSA = aSAR->RelatedShapeAspect();
3856               if (!aSA.IsNull()) {
3857                 if (aSA->IsKind(STANDARD_TYPE(StepDimTol_Datum)) ||
3858                   aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumTarget)) ||
3859                   aSA->IsKind(STANDARD_TYPE(StepDimTol_DatumFeature)) ||
3860                   aSA->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp))) {
3861                   isConnectedToGDT = Standard_True;
3862                 }
3863                 for (Interface_EntityIterator aDimIter = aGraph.Sharings(aSA); aDimIter.More() && !isConnectedToGDT; aDimIter.Next()) {
3864                   if (aDimIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) ||
3865                     aDimIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
3866                     aDimIter.Value()->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3867                     isConnectedToGDT = Standard_True;
3868                     continue;
3869                   }
3870                 }
3871               }
3872             }
3873           }
3874           if (isConnectedToGDT)
3875             continue;
3876         }
3877         else if (aDMIA->Definition().PropertyDefinition().IsNull())
3878           continue;
3879
3880         // Get shapes
3881         NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
3882         collectShapeAspect(aDefinition, theWS, aSAs);
3883         for (Standard_Integer aSAIt = 1; aSAIt <= aSAs.Length(); aSAIt++) {
3884           Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
3885           for (Interface_EntityIterator anIter = aGraph.Sharings(aSAs.Value(aSAIt)); anIter.More() && aGISU.IsNull(); anIter.Next())
3886             aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIter.Value());
3887           if (aGISU.IsNull())
3888             continue;
3889           for (Standard_Integer anItemIt = 1; anItemIt <= aGISU->NbIdentifiedItem(); anItemIt++) {
3890             TDF_Label aLabel = getShapeLabel(aGISU->IdentifiedItemValue(anItemIt), theWS, XCAFDoc_DocumentToo