summaryrefslogtreecommitdiff
path: root/src/XCAFDoc/XCAFDoc_ShapeTool.cxx
blob: 13cc47dae89f3e9f2d52010e2380139c81e29535 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
// File:	XCAFDoc_ShapeTool.cxx
// Created:	Thu Aug  3 15:23:53 2000
// Author:	data exchange team
//	 	<det@zamox.nnov.matra-dtv.fr>


#include <XCAFDoc_ShapeTool.ixx>
#include <XCAFDoc.hxx>

#include <TDF_Tool.hxx>
#include <TDF_Label.hxx>
#include <TDF_LabelMap.hxx>
#include <TDF_LabelSequence.hxx>
#include <TDF_ChildIterator.hxx>
#include <TDF_ChildIDIterator.hxx>
#include <TDF_MapIteratorOfLabelMap.hxx>

#include <TDataStd_Name.hxx>
#include <TDataStd_TreeNode.hxx>
#include <TDataStd_ChildNodeIterator.hxx>
#include <TDataStd_UAttribute.hxx>

#include <TDocStd_Document.hxx>

#include <TNaming_Builder.hxx>
#include <TNaming_NamedShape.hxx>
#include <TNaming_Tool.hxx>

#include <TopLoc_Location.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Compound.hxx>
#include <BRep_Builder.hxx>
#include <XCAFDoc_Location.hxx>

#include <TCollection_AsciiString.hxx>
#include <TCollection_HAsciiString.hxx>
#include <TCollection_ExtendedString.hxx>
#include <TColStd_SequenceOfHAsciiString.hxx>
#include <XCAFDoc_GraphNode.hxx>
#include <TopLoc_IndexedMapOfLocation.hxx>
#include <gp_Trsf.hxx>
#include <gp_Pnt.hxx>
#include <XCAFDoc_ShapeMapTool.hxx>

#define AUTONAMING // automatically set names for labels

// attribute methods //////////////////////////////////////////////////

//=======================================================================
//function : GetID
//purpose  : 
//=======================================================================

const Standard_GUID& XCAFDoc_ShapeTool::GetID() 
{
  static Standard_GUID ShapeToolID ("efd212ee-6dfd-11d4-b9c8-0060b0ee281b");
  return ShapeToolID; 
}


//=======================================================================
//function : Set
//purpose  : 
//=======================================================================

Handle(XCAFDoc_ShapeTool) XCAFDoc_ShapeTool::Set(const TDF_Label& L) 
{
  Handle(XCAFDoc_ShapeTool) A;
  if (!L.FindAttribute (XCAFDoc_ShapeTool::GetID(), A)) {
    A = new XCAFDoc_ShapeTool ();
    L.AddAttribute(A);
  }
  A->Init();
  return A;
}


//=======================================================================
//function : Constructor
//purpose  : 
//=======================================================================

XCAFDoc_ShapeTool::XCAFDoc_ShapeTool()
{
  hasSimpleShapes = Standard_False;
}


//=======================================================================
//function : ID
//purpose  : 
//=======================================================================

const Standard_GUID& XCAFDoc_ShapeTool::ID() const
{
  return GetID();
}

//=======================================================================
//function : Restore
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::Restore(const Handle(TDF_Attribute)& /*with*/) 
{
}

//=======================================================================
//function : NewEmpty
//purpose  : 
//=======================================================================

Handle(TDF_Attribute) XCAFDoc_ShapeTool::NewEmpty() const
{
  return new XCAFDoc_ShapeTool;
}

//=======================================================================
//function : Paste
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::Paste (const Handle(TDF_Attribute)& /*into*/,
			       const Handle(TDF_RelocationTable)& /*RT*/) const
{
}

#ifdef AUTONAMING
// Auxiliary methods //////////////////////////////////////////////////

//=======================================================================
//function : SetLabelNameByLink
//purpose  : 
//=======================================================================
static void SetLabelNameByLink(const TDF_Label L) 
{
  Handle(TDataStd_TreeNode) Node;
  if (! L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) ||
      ! Node->HasFather()) {
    cout<<"Error: XCAFDoc_ShapeTool, SetLabelNameByLink(): NO NODE"<<endl;
    return;
  }
  TCollection_AsciiString Entry;
  TDF_Tool::Entry ( Node->Father()->Label(), Entry );
  Entry.Insert(1, "=>[");
  Entry += "]";

  TDataStd_Name::Set(L, TCollection_ExtendedString( Entry ));
}


//=======================================================================
//function : SetLabelNameByShape
//purpose  : 
//=======================================================================
static void SetLabelNameByShape(const TDF_Label L) 
{
  TopoDS_Shape S;
  if (XCAFDoc_ShapeTool::GetShape(L, S) &&
      ! L.IsAttribute(TDataStd_Name::GetID()) ) {
    Standard_SStream Stream;
//    TopAbs_ShapeEnum Type = S.ShapeType();
//    if (Type == TopAbs_COMPOUND) Stream<<"ASSEMBLY";
//    else 
    TopAbs::Print(S.ShapeType(), Stream);
   
#ifdef USE_STL_STREAM    
    TCollection_AsciiString aName (Stream.str().c_str());
#else
    Stream << ends;
    TCollection_AsciiString aName (Stream.str());
#endif    
    TDataStd_Name::Set(L, TCollection_ExtendedString(aName));
  }
}
#endif


//=======================================================================
//function : SearchUsingMap
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::SearchUsingMap(const TopoDS_Shape &S, TDF_Label &L,
                                                   const Standard_Boolean findWithoutLoc,
                                                   const Standard_Boolean findSubShape) const
{

  if(myShapeLabels.IsBound(S)) {
    L = myShapeLabels.Find(S);
    return Standard_True;
  }
  TopoDS_Shape S0 = S;
  TopLoc_Location loc;
  S0.Location(loc);
  if(myShapeLabels.IsBound(S0)) {
    TDF_Label L1 = myShapeLabels.Find(S0);
    TDF_LabelSequence Labels;
    if(GetUsers(L1, Labels, Standard_True)) {
      for(Standard_Integer i=1; i<=Labels.Length(); i++) {
        TopoDS_Shape c = GetShape(Labels.Value(i));
        if(c.IsSame(S)) {
          L = Labels.Value(i);
          return Standard_True;
        }
      }
    }
    if(findWithoutLoc) {
      L = L1;
      return Standard_True;
    }
  }

  if(hasSimpleShapes) {
    if(mySimpleShapes.IsBound(S)) {
      L = mySimpleShapes.Find(S);
      return Standard_True;
    }
    if(mySimpleShapes.IsBound(S0)) {
      L = mySimpleShapes.Find(S0);
      return Standard_True;
    }
  }
  // search subshapes
  if(!findSubShape) return Standard_False;
  TDF_Label mainL = FindMainShapeUsingMap(S);
  if(mainL.IsNull()) return Standard_False;
  L = AddSubShape(mainL,S);
  return !L.IsNull();//Standard_True;
}


//=======================================================================
//function : Search
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::Search (const TopoDS_Shape &S, 
					 TDF_Label &L,
					 const Standard_Boolean findInstance,
					 const Standard_Boolean findComponent,
					 const Standard_Boolean findSubShape) const
{
  // search among shapes
  Standard_Boolean isLocated = ! S.Location().IsIdentity();
  
  if ( isLocated ) {
    // try to find top-level instance
    if ( findInstance && FindShape ( S, L, Standard_True ) )
      return Standard_True;
    // try to find component of assembly
    if ( findComponent ) {
      TDF_LabelSequence labels;
      GetShapes ( labels );
      for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
	if ( ! IsAssembly ( labels.Value(i) ) ) continue;
	TDF_LabelSequence comp;
	GetComponents ( labels.Value(i), comp );
	for ( Standard_Integer j=1; j <= comp.Length(); j++ ) {
	  TopoDS_Shape c = GetShape ( comp.Value(j) );
	  if ( c.IsSame ( S ) ) {
	    L = comp.Value(j);
	    return Standard_True;
	  }
	}
      }
    }
  }
  // try to find top-level simple shape
  if ( FindShape ( S, L, Standard_False ) ) return Standard_True;
  
  // search subshapes
  if ( ! findSubShape ) return Standard_False;
  TDF_Label mainL = FindMainShape ( S );
  if ( mainL.IsNull() ) return Standard_False;
  L = AddSubShape ( mainL, S );
  return !L.IsNull();//Standard_True;
}

//=======================================================================
//function : FindShape
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::FindShape (const TopoDS_Shape& S, 
					       TDF_Label& L,
					       const Standard_Boolean findInstance) const
{
  // search for null-located shape
  TopoDS_Shape S0 = S;
  if ( ! findInstance ) {
    TopLoc_Location loc;
    S0.Location ( loc );
  }

  // this code is used instead of the following for performance reasons
  if (TNaming_Tool::HasLabel(Label(), S0)) {
    int TransDef = 0;
    L = TNaming_Tool::Label(Label(), S0, TransDef);
    return Standard_True;
  }
/*
  TDF_ChildIDIterator it(myLabel,TNaming_NamedShape::GetID());
  for (; it.More(); it.Next()) {
    TDF_Label aLabel = it.Value()->Label();
    Handle(TNaming_NamedShape) NS;
    if ( aLabel.FindAttribute(TNaming_NamedShape::GetID(), NS) &&
	 S0.IsSame ( TNaming_Tool::GetShape(NS) ) ) {
      L = aLabel;
      return Standard_True;
    }
  }
*/
  return Standard_False;
}

//=======================================================================
//function : FindShape
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::FindShape (const TopoDS_Shape& S,
				     const Standard_Boolean findInstance) const
{
  TDF_Label L;
  FindShape ( S, L, findInstance );
  return L;
}

//=======================================================================
//function : GetShape
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::GetShape (const TDF_Label& L, TopoDS_Shape& S) 
{
  Handle(XCAFDoc_Location) LocationAttribute;

  if(IsExternRef(L)) {
    TopoDS_Compound EmptyComp;
    BRep_Builder B;
    B.MakeCompound(EmptyComp);
    S = EmptyComp;
  }

  // for instance, get referred shape
  Handle(TDataStd_TreeNode) Node;
  if ( L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) && Node->HasFather() && 
       L.FindAttribute(XCAFDoc_Location::GetID(), LocationAttribute)) {
    if ( ! GetShape(Node->Father()->Label(), S) ) return Standard_False;
    S.Move ( LocationAttribute->Get() );
    return Standard_True;
  }

  // else just return shape on this label
  Handle(TNaming_NamedShape) NS;
  if ( ! L.FindAttribute(TNaming_NamedShape::GetID(), NS) ) return Standard_False;
  S = TNaming_Tool::GetShape(NS);
  return Standard_True;
}

//=======================================================================
//function : GetShape
//purpose  : 
//=======================================================================

TopoDS_Shape XCAFDoc_ShapeTool::GetShape(const TDF_Label& L) 
{
  TopoDS_Shape aShape;
  GetShape(L,aShape);
  return aShape;
}

//=======================================================================
//function : NewShape
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::NewShape() const
{
  TopoDS_Compound aShape;
  BRep_Builder tdsB;
  tdsB.MakeCompound ( aShape );

  TDF_TagSource aTag;
  TDF_Label aLabel = aTag.NewChild(Label());
  
  TNaming_Builder tnBuild(aLabel);
  tnBuild.Generated(aShape);
  
  return aLabel;
}

//=======================================================================
//function : SetShape
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::SetShape (const TDF_Label& L, const TopoDS_Shape& S)
{
  TNaming_Builder tnBuild(L);
  tnBuild.Generated(S);
  Handle(XCAFDoc_ShapeMapTool) A = XCAFDoc_ShapeMapTool::Set(L);
//  if ( ! L.FindAttribute(XCAFDoc_ShapeMapTool::GetID(), A) ) {
//    A = XCAFDoc_ShapeMapTool::Set(L);
//    L.AddAttribute(A);
//  }
  A->SetShape(S);

  if(!myShapeLabels.IsBound(S)) {
    myShapeLabels.Bind(S,L);
  }
  
  //:abv 31.10.01: update assemblies that refer a shape
  TDF_LabelSequence Labels;
  if ( GetUsers ( L, Labels, Standard_True ) ) {
    for ( Standard_Integer i=Labels.Length(); i >=1; i-- ) 
      UpdateAssembly ( Labels(i) );
  }
}

//=======================================================================
//function : MakeReference
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::MakeReference (const TDF_Label &L, 
				    const TDF_Label &refL,
				    const TopLoc_Location &loc)
{
  // store location
  XCAFDoc_Location::Set(L, loc);
    
    // set reference
  Handle(TDataStd_TreeNode) refNode, mainNode;
  mainNode = TDataStd_TreeNode::Set ( refL, XCAFDoc::ShapeRefGUID() );
  refNode  = TDataStd_TreeNode::Set ( L,    XCAFDoc::ShapeRefGUID() );
  refNode->Remove(); // abv: fix against bug in TreeNode::Append()
  mainNode->Append(refNode);

#ifdef AUTONAMING
  SetLabelNameByLink(L);
#endif
}

//=======================================================================
//function : addShape
//purpose  : private
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::addShape (const TopoDS_Shape& S, const Standard_Boolean makeAssembly)
{
  TDF_Label ShapeLabel;
  TDF_TagSource aTag;

  // search if the shape already exists (with the same location)
  if ( S.IsNull() || FindShape ( S, ShapeLabel, Standard_True ) ) return ShapeLabel;
  
  // else add a new label
  ShapeLabel = aTag.NewChild(Label());
  
  // if shape has location, make a reference to the same shape without location
  if ( ! S.Location().IsIdentity() /*&& FindShape ( S, L )*/ ) {
    TopoDS_Shape S0 = S;
    TopLoc_Location loc;
    S0.Location ( loc );
    TDF_Label L = addShape ( S0, makeAssembly );
    MakeReference ( ShapeLabel, L, S.Location() );
    return ShapeLabel;
  }
  
  // else add a shape to a label
  TNaming_Builder tnBuild(ShapeLabel);
  tnBuild.Generated(S);
  
  Handle(XCAFDoc_ShapeMapTool) A = XCAFDoc_ShapeMapTool::Set(ShapeLabel);
//  if ( ! ShapeLabel.FindAttribute(XCAFDoc_ShapeMapTool::GetID(), A) ) {
//    A = XCAFDoc_ShapeMapTool::Set(ShapeLabel);
//    ShapeLabel.AddAttribute(A);
//  }
  A->SetShape(S);
  
#ifdef AUTONAMING
  SetLabelNameByShape(ShapeLabel);
#endif

  // if shape is Compound and flag is set, create assembly
  if ( makeAssembly && S.ShapeType() == TopAbs_COMPOUND ) {
    // mark assembly by assigning UAttribute
    Handle(TDataStd_UAttribute) Uattr;
    Uattr = TDataStd_UAttribute::Set ( ShapeLabel, XCAFDoc::AssemblyGUID() );
#ifdef AUTONAMING
    TDataStd_Name::Set(ShapeLabel, TCollection_ExtendedString("ASSEMBLY"));
#endif

    // iterate on components
    TopoDS_Iterator Iterator(S);
    for (; Iterator.More(); Iterator.Next()) {
      // get label for component`s shape
      TopoDS_Shape Scomp = Iterator.Value(), S0 = Scomp;
      TopLoc_Location loc;
      S0.Location ( loc );
      TDF_Label compL = addShape ( S0, makeAssembly );
      
      // add a component as reference
      TDF_Label RefLabel = aTag.NewChild(ShapeLabel);
      MakeReference ( RefLabel, compL, Scomp.Location() );
    }
  }
  
  if(!IsAssembly(ShapeLabel)) {
    //const TopTools_IndexedMapOfShape tmpMap = A->GetMap();
    //for(Standard_Integer i=1; i<=tmpMap.Extent(); i++)
    //mySubShapes.Bind(tmpMap.FindKey(i),ShapeLabel);
    for(Standard_Integer i=1; i<=A->GetMap().Extent(); i++)
    mySubShapes.Bind(A->GetMap().FindKey(i),ShapeLabel);
    //mySubShapes.Bind(ShapeLabel,A->GetMap());
  }

  return ShapeLabel;
}


//=======================================================================
//function : prepareAssembly
//purpose  : auxilary
//=======================================================================
static Standard_Boolean prepareAssembly (const TopoDS_Shape& theShape,
                                         TopoDS_Shape& theOUTShape)
{
  // iterate on components
  theOUTShape = theShape;
  if (theShape.ShapeType() == TopAbs_COMPOUND) {
    BRep_Builder B;
    // check if shape if frosen
    if (!theOUTShape.Free())
      theOUTShape.Free(Standard_True);
    
    TopTools_SequenceOfShape aSubShapeSeq;
    TopoDS_Iterator Iterator(theShape);
    for (; Iterator.More(); Iterator.Next())
      aSubShapeSeq.Append(Iterator.Value());
    for (Standard_Integer i = 1; i <= aSubShapeSeq.Length(); i++) {
      TopoDS_Shape Scomp = aSubShapeSeq.Value(i);
      TopoDS_Shape aNewScomp;
      B.Remove(theOUTShape, Scomp);
      prepareAssembly( Scomp, aNewScomp );
      TopLoc_Location aLoc;
      aLoc = aNewScomp.Location();
      if ( aLoc.IsIdentity() ) {
        // create an "empty" location
        gp_Trsf aTrsf;
        aTrsf.SetScale(gp_Pnt(0,0,0), 1);
        aLoc = TopLoc_Location( aTrsf );
        aNewScomp.Location( aLoc );
      }
      B.Add(theOUTShape, aNewScomp);
    }
  }
  return Standard_True;
}


//=======================================================================
//function : AddShape
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::AddShape (const TopoDS_Shape& theShape,
                                       const Standard_Boolean makeAssembly,
                                       const Standard_Boolean makePrepare)
{
  // PTV 17.02.2003 to avoid components without location.
  TopoDS_Shape S = theShape;
  if ( makePrepare && makeAssembly && S.ShapeType() == TopAbs_COMPOUND )
    prepareAssembly( theShape, S ); // OCC1669
  
  TDF_Label L = addShape(S,makeAssembly);

  if(!myShapeLabels.IsBound(S)) {
    myShapeLabels.Bind(S,L);
  }

  return L;

  //return addShape( S, makeAssembly );
}

//=======================================================================
//function : RemoveShape
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::RemoveShape (const TDF_Label& L) const
{
  if ( ! IsTopLevel ( L ) || ! IsFree ( L ) ) return Standard_False;
  L.ForgetAllAttributes (Standard_True);
  return Standard_True;
}


//=======================================================================
//function : Init
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::Init()
{
  hasSimpleShapes = Standard_False;
}


//=======================================================================
//function : ComputeShapes
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::ComputeShapes(const TDF_Label& L)
{
  TDF_ChildIterator it(L); 
  for(; it.More(); it.Next()) {
    TDF_Label L1 = it.Value();
    TopoDS_Shape S;
    if(GetShape(L1,S)) {
      if(!myShapeLabels.IsBound(S)) {
        mySimpleShapes.Bind(S,L1);
      }
    }
    ComputeShapes(L1);
  }
}


//=======================================================================
//function : ComputeSimpleShapes
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::ComputeSimpleShapes()
{
  ComputeShapes(Label());
  hasSimpleShapes = Standard_True;
}


//=======================================================================
//function : GetShapes
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::GetShapes(TDF_LabelSequence& Labels) const
{
  Labels.Clear();

  TDF_ChildIterator it(Label()); 
  for (; it.More(); it.Next()) {
    TDF_Label L = it.Value();
    TopoDS_Shape S;
    if ( GetShape ( L, S ) ) Labels.Append ( L );
  }
}


//=======================================================================
//function : GetFreeShapes
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::GetFreeShapes (TDF_LabelSequence& FreeLabels) const
{
  FreeLabels.Clear();

  TDF_ChildIterator it(Label());
  for (; it.More(); it.Next()) {
    TDF_Label L = it.Value();
    TopoDS_Shape S;
    if ( GetShape ( L, S ) && IsFree ( L ) ) FreeLabels.Append ( L );
  }
}

//=======================================================================
//function : IsTopLevel
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsTopLevel (const TDF_Label& L) const
{
  return L.Father() == Label();
}

//=======================================================================
//function : IsShape
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsShape (const TDF_Label& L) 
{
  return IsSimpleShape ( L ) || IsAssembly ( L ) || IsReference ( L );
}

//=======================================================================
//function : IsSimpleShape
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsSimpleShape (const TDF_Label& L) 
{
  Handle(TNaming_NamedShape) NS;
  return L.FindAttribute ( TNaming_NamedShape::GetID(), NS ) &&
         ! IsAssembly ( L ) && ! IsReference ( L );
}

//=======================================================================
//function : IsReference
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsReference (const TDF_Label& L)
{
  Handle(TDataStd_TreeNode) Node;
  return L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) && Node->HasFather();
}

//=======================================================================
//function : IsAssembly
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsAssembly (const TDF_Label& L) 
{
  Handle(TDataStd_UAttribute) Uattr;
  return L.FindAttribute(XCAFDoc::AssemblyGUID(), Uattr);
}

//=======================================================================
//function : IsComponent
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsComponent (const TDF_Label& L)
{
  return IsReference ( L ) && IsAssembly ( L.Father() );
}

//=======================================================================
//function : IsCompound
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsCompound (const TDF_Label& L) 
{
  Handle(TDataStd_Name) Name;
  if (L.FindAttribute(TDataStd_Name::GetID(),Name)) {
    TCollection_ExtendedString estr1 = Name->Get();
    TCollection_ExtendedString estr2("COMPOUND");
    if(estr1==estr2) {
      return Standard_True;
    }
  }
  return Standard_False;
}

//=======================================================================
//function : IsSubShape
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsSubShape (const TDF_Label& L)
{
  return IsSimpleShape ( L ) && IsShape ( L.Father() );
}

//=======================================================================
//function : IsFree
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsFree (const TDF_Label& L) 
{
  Handle(TDataStd_TreeNode) Node;
  if ( ! L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) || 
       ! Node->HasFirst() ) return Standard_True;

  return Standard_False;
}

//=======================================================================
//function : GetUsers
//purpose  : Returns number of users (0 if shape is free)
//=======================================================================

Standard_Integer XCAFDoc_ShapeTool::GetUsers (const TDF_Label& L, 
					      TDF_LabelSequence& Labels,
					      const Standard_Boolean getsubchilds)
{
  Standard_Integer NbUsers=0;
  Handle(TDataStd_TreeNode) Node  ;

  if ( ! L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) ) return NbUsers;
  
  Node = Node->First();
  while ( ! Node.IsNull() ) {
    
    if ( getsubchilds ) {
      TDF_Label underL = Node->Label().Father();
      NbUsers += GetUsers ( underL, Labels, getsubchilds );
    }
    
    Labels.Append(Node->Label());
    Node = Node->Next();
    NbUsers++;
  }
  return NbUsers;
}
  
//=======================================================================
//function : NbComponents
//purpose  : 
//=======================================================================

Standard_Integer XCAFDoc_ShapeTool::NbComponents (const TDF_Label& L,
						  const Standard_Boolean getsubchilds) 
{
  TDF_LabelSequence subLabels;
  GetComponents (L, subLabels, getsubchilds);
  return subLabels.Length();
}

//=======================================================================
//function : GetComponents
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::GetComponents (const TDF_Label& L, TDF_LabelSequence& Labels,
						   const Standard_Boolean getsubchilds) 
{
  if ( ! IsAssembly(L) ) return Standard_False;
  
  TDF_ChildIterator It(L);
  for (; It.More(); It.Next() ) {
    TDF_Label comp = It.Value();
    if ( IsComponent ( comp ) ) {
      if ( getsubchilds ) {
	TDF_Label underL;
	if ( GetReferredShape ( comp, underL ) )
	  GetComponents ( underL, Labels, getsubchilds);
      }
      Labels.Append ( comp );
    }
  }
  return Standard_True;
}

//=======================================================================
//function : GetLocation
//purpose  : 
//=======================================================================

TopLoc_Location XCAFDoc_ShapeTool::GetLocation (const TDF_Label& L)
{
  Handle(XCAFDoc_Location) LocationAttribute;
  if (L.FindAttribute(XCAFDoc_Location::GetID(), LocationAttribute)) 
    return LocationAttribute->Get();
  
  Handle(TNaming_NamedShape) NS;
  TopoDS_Shape S;
  if ( L.FindAttribute ( TNaming_NamedShape::GetID(), NS ) ) {
    S = TNaming_Tool::GetShape(NS);
  }
  return S.Location();
}

//=======================================================================
//function : GetReferredShape
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::GetReferredShape (const TDF_Label& L, 
						      TDF_Label& Label)
{
  if ( ! IsReference(L) ) return Standard_False;
  
  Handle (TDataStd_TreeNode) Node;
  L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node);
  Label = Node->Father()->Label();
  return Standard_True;
}

//=======================================================================
//function : AddComponent
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::AddComponent (const TDF_Label& assembly, 
					   const TDF_Label& compL, 
					   const TopLoc_Location &Loc) const
{
  TDF_Label L;
  
  // check that shape is assembly
  if ( ! IsAssembly(assembly) ) {
    // if it is simple shape, make it assembly
    if ( IsSimpleShape(assembly) ) 
      TDataStd_UAttribute::Set ( assembly, XCAFDoc::AssemblyGUID() );
    else return L;
  }
  
  // add a component as reference
  TDF_TagSource aTag;
  L = aTag.NewChild(assembly);
  MakeReference ( L, compL, Loc );

  // update assembly`s TopoDS_Shape
  UpdateAssembly ( assembly );
  return L;
}

//=======================================================================
//function : AddComponent
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::AddComponent (const TDF_Label& assembly, 
					   const TopoDS_Shape& comp,
					   const Standard_Boolean expand)
{
  // get label for component`s shape
  TopoDS_Shape S0 = comp;
  TopLoc_Location loc;
  S0.Location ( loc );
  TDF_Label compL;
  compL = AddShape ( S0, expand );
  
  // add component by its label
  return AddComponent ( assembly, compL, comp.Location() );
}

//=======================================================================
//function : RemoveComponent
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::RemoveComponent (const TDF_Label& comp) const
{
  if ( IsComponent(comp) ) {
    comp.ForgetAllAttributes();
    UpdateAssembly(comp.Father());
  }
}

//=======================================================================
//function : UpdateAssembly
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::UpdateAssembly (const TDF_Label& L) const
{
  if ( ! IsAssembly(L) ) return;

  TopoDS_Compound newassembly;
  BRep_Builder b;
  b.MakeCompound(newassembly);

  TDF_ChildIterator chldLabIt(L);
  for (; chldLabIt.More(); chldLabIt.Next() ) {
    TDF_Label subLabel = chldLabIt.Value();
    if ( IsComponent ( subLabel ) ) {
      b.Add(newassembly, GetShape(subLabel));
    }
  }
  TNaming_Builder tnBuild(L);
  tnBuild.Generated(newassembly);
}

//=======================================================================
//function : IsSubShape
//purpose  : 
//=======================================================================

//static Standard_Boolean CheckSubShape (const TopoDS_Shape &S, const TopoDS_Shape &sub)
//{
//  if ( S.IsSame ( sub ) ) return Standard_True;
//  
//  if ( S.ShapeType() >= sub.ShapeType() ) return Standard_False;
//  
//  for ( TopoDS_Iterator it(S); it.More(); it.Next() ) {
//    if ( CheckSubShape ( it.Value(), sub ) ) return Standard_True;
//  }
//  return Standard_False;
//}

//=======================================================================
//function : IsSubShape
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsSubShape (const TDF_Label &shapeL,
					     const TopoDS_Shape &sub) const
{
  Handle(XCAFDoc_ShapeMapTool) A;
  if ( ! shapeL.FindAttribute(XCAFDoc_ShapeMapTool::GetID(), A) )
    return Standard_False;
  
  //TopoDS_Shape S = GetShape ( shapeL );
  //return ! S.IsNull() && CheckSubShape ( S, sub );
  
  return A->IsSubShape(sub);
}

//=======================================================================
//function : FindSubShape
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::FindSubShape (const TDF_Label &shapeL,
                                                  const TopoDS_Shape &sub,
                                                  TDF_Label &L) const
{
  // this code is used instead of the following for performance reasons
  if ( TNaming_Tool::HasLabel(Label(), sub) ) {
    int TransDef = 0;
    L = TNaming_Tool::Label(Label(), sub, TransDef);
    return ( ! L.IsNull() && L.Father() == shapeL );
  }

/*
  TDF_ChildIterator chldLabIt(shapeL);
  for (; chldLabIt.More(); chldLabIt.Next() ) {
    TDF_Label subLabel = chldLabIt.Value();
    TopoDS_Shape S;
    if ( GetShape ( subLabel, S ) && S.IsSame ( sub ) ) {
      L = subLabel;
      return Standard_True;
    }
  }
*/
  return Standard_False;
}

//=======================================================================
//function : AddSubShape
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::AddSubShape (const TDF_Label &shapeL,
                                          const TopoDS_Shape &sub) const
{
  TDF_Label L;
  if ( FindSubShape ( shapeL, sub, L ) ) return L;
  
  if ( ! IsSubShape ( shapeL, sub ) ) return L;
  
  TDF_TagSource aTag;
  L = aTag.NewChild(shapeL);
  
  TNaming_Builder tnBuild(L);
  tnBuild.Generated(sub);

//  if(!mySubShapes.IsBound(sub))
//    mySubShapes.Bind(sub,L);
   
  return L;
}


//=======================================================================
//function : FindMainShapeUsingMap
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::FindMainShapeUsingMap(const TopoDS_Shape &sub) const
{
  //for(Standard_Integer i=1; i<=myNotAssemblies.Length(); i++) {
  //  TDF_Label L = myNotAssemblies.Value(i);
  //  if(IsSubShape(L,sub)) return L;
  //}
  if(mySubShapes.IsBound(sub))
    return mySubShapes.Find(sub);
  TDF_Label L0;
  return L0;
}


//=======================================================================
//function : FindMainShape
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::FindMainShape (const TopoDS_Shape &sub) const
{
  TDF_ChildIterator it(Label());
  for (; it.More(); it.Next()) {
    TDF_Label L = it.Value();
    if ( ! IsAssembly ( L ) && IsSubShape ( L, sub ) ) return L;
  }
  TDF_Label L0;
  return L0;
}


//=======================================================================
//function : GetSubShapes
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::GetSubShapes (const TDF_Label &L, 
					       TDF_LabelSequence& Labels)
{
  TDF_ChildIterator It(L);
  for (; It.More(); It.Next() ) {
    TDF_Label sub = It.Value();
    if ( IsSubShape ( sub ) ) Labels.Append ( sub );
  }
  return Labels.Length() >0;
}

//=======================================================================
//function : BaseLabel
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::BaseLabel () const
{
  return Label();
}

//=======================================================================
//function : DumpAssembly
//purpose  : recursive part of Dump()
//=======================================================================

static void DumpAssembly(const TDF_Label L,
			 const Standard_Integer level,
			 const Standard_Boolean deep)
{
  for (Standard_Integer i=0; i<level; i++)
    cout<<"\t";
  
  TCollection_AsciiString Entry;
  TDF_Tool::Entry(L, Entry);

  cout<<"ASSEMBLY "<<Entry;
  Handle(TDataStd_Name) Name;
  if (L.FindAttribute(TDataStd_Name::GetID(), Name))
    cout<<" "<<Name->Get();
  
  if (deep) {
    TopoDS_Shape S;
    XCAFDoc_ShapeTool::GetShape(L, S);
    cout<<"("<<*(void**)&S.TShape();
    if (! S.Location().IsIdentity())
      cout<<", "<< *(void**)&S.Location();
    cout<<") ";
  }
  cout<<endl;
  
  Handle(TDataStd_TreeNode) Node;
  TDF_ChildIDIterator NodeIterator(L, XCAFDoc::ShapeRefGUID());
  for (; NodeIterator.More(); NodeIterator.Next()) {
    Node = Handle(TDataStd_TreeNode)::DownCast(NodeIterator.Value());
    if (Node->HasFather()) {
      if (Node->Father()->Label().HasChild())
	DumpAssembly(Node->Father()->Label(), level+1, deep);
      else {
	XCAFDoc_ShapeTool::DumpShape(Node->Father()->Label(), level+1, deep);
	  cout<<endl;
	}
    }
  }
}

//=======================================================================
//function : Dump
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::Dump(const Standard_Boolean deep) const
{
  Standard_Integer level = 0;
//   TopTools_SequenceOfShape SeqShapes;
  TDF_LabelSequence SeqLabels;
  GetShapes( SeqLabels);

  if (SeqLabels.Length()>0) cout<<endl;
  Standard_Integer i;
  for (i=1; i<=SeqLabels.Length(); i++) {
    DumpAssembly(SeqLabels.Value(i), level, deep);
  }

  SeqLabels.Clear();
  GetFreeShapes(SeqLabels);
  cout<<endl<<"Free Shapes: "<<SeqLabels.Length()<<endl;
  for (i = 1; i<=SeqLabels.Length(); i++) {
    DumpShape(SeqLabels.Value(i), level, deep);
    cout<<endl;
  }
}

//=======================================================================
//function : DumpShape
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::DumpShape(const TDF_Label& L,const Standard_Integer level,const Standard_Boolean deep) 
{
  TopoDS_Shape S;
  if(! XCAFDoc_ShapeTool::GetShape(L, S) ) return;
  for (Standard_Integer i=0; i<level; i++)
    cout<<"\t";
  
  if (S.ShapeType() == TopAbs_COMPOUND) cout<<"ASSEMBLY";
  else TopAbs::Print(S.ShapeType(), cout);
  
  TCollection_AsciiString Entry;
  TDF_Tool::Entry(L, Entry);
  cout<<"  "<<Entry;
  //cout<<endl;
  Handle(TDataStd_Name) Name;
  if (L.FindAttribute(TDataStd_Name::GetID(),Name)) 
    cout<<" "<<Name->Get();
  
  if (deep) {
    cout<<"("<<*(void**)&S.TShape();
    if (! S.Location().IsIdentity())
      cout<<", "<< *(void**)&S.Location();
    cout<<") ";
  }
}

//=======================================================================
//function : IsExternRef
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::IsExternRef(const TDF_Label& L) 
{
  Handle(TDataStd_UAttribute) Uattr;
  return L.FindAttribute(XCAFDoc::ExternRefGUID(), Uattr);
}

//=======================================================================
//function : SetExternRefs
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::SetExternRefs(const TDF_Label& L,
                                      const TColStd_SequenceOfHAsciiString& SHAS) const
{
  TDF_Label ShapeLabel = L.NewChild();
  TDataStd_UAttribute::Set(ShapeLabel,XCAFDoc::ExternRefGUID());
  for(Standard_Integer i=1; i<=SHAS.Length(); i++) {
    TDF_Label tmplbl = ShapeLabel.FindChild(i,Standard_True);
    Handle(TCollection_HAsciiString) str = SHAS(i);
    TCollection_ExtendedString extstr(str->String());
    TDataStd_Name::Set(tmplbl,extstr);
  }
}

//=======================================================================
//function : SetExternRefs
//purpose  : 
//=======================================================================

TDF_Label XCAFDoc_ShapeTool::SetExternRefs(const TColStd_SequenceOfHAsciiString& SHAS) const
{
  TDF_Label ShapeLabel;
  TDF_TagSource aTag;
  // add a new label
  ShapeLabel = aTag.NewChild(Label());
  TDataStd_UAttribute::Set(ShapeLabel,XCAFDoc::ExternRefGUID());
  for(Standard_Integer i=1; i<=SHAS.Length(); i++) {
    TDF_Label tmplbl = ShapeLabel.FindChild(i,Standard_True);
    Handle(TCollection_HAsciiString) str = SHAS(i);
    TCollection_ExtendedString extstr(str->String());
    TDataStd_Name::Set(tmplbl,extstr);
  }
  return ShapeLabel;
}

//=======================================================================
//function : GetExternRefs
//purpose  : 
//=======================================================================

void XCAFDoc_ShapeTool::GetExternRefs(const TDF_Label& L,
                                      TColStd_SequenceOfHAsciiString& SHAS)
{
  Handle(TDataStd_Name) TDN;
  TDF_Label tmplbl;
  for(Standard_Integer i=1; i<=L.NbChildren(); i++) {
    tmplbl = L.FindChild(i);
    if(tmplbl.FindAttribute(TDataStd_Name::GetID(),TDN)) {
      TCollection_ExtendedString extstr = TDN->Get();
      Handle(TCollection_HAsciiString) str = 
	new TCollection_HAsciiString(TCollection_AsciiString(extstr, '?')); 
      SHAS.Append(str);
    }
  }
}

// API: API work with SHUO (Specified Higher Usage Occurrance) structure

//=======================================================================
//function : GetSHUO
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::GetSHUO (const TDF_Label& SHUOLabel,
                                      Handle(XCAFDoc_GraphNode)& aSHUOAttr)
{
  if ( !SHUOLabel.FindAttribute( XCAFDoc::SHUORefGUID(), aSHUOAttr ) )
    return Standard_False;
  return Standard_True;
}

//=======================================================================
//function : GetAllComponentSHUO
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::GetAllComponentSHUO (const TDF_Label& theCompLabel,
                                                         TDF_AttributeSequence& theSHUOAttrs)
{
  TDF_ChildIterator it(theCompLabel); 
  for (; it.More(); it.Next()) {
    TDF_Label L = it.Value();
    Handle(XCAFDoc_GraphNode) aSHUOAttr;
    if ( GetSHUO( L, aSHUOAttr ) )
      theSHUOAttrs.Append( aSHUOAttr );
  }
  return (theSHUOAttrs.Length() > 0);
}

//=======================================================================
//function : SetSHUO
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::SetSHUO (const TDF_LabelSequence& labels,
                                             Handle(XCAFDoc_GraphNode)& MainSHUOAttr) const
{
  MainSHUOAttr.Nullify();
  // check number of labels
  if (labels.Length() < 2)
    return Standard_False;
  // check is all labels contains components of any assemblyies 
  Standard_Integer i;
  for (i = 1; i <= labels.Length(); i++)
    if ( !IsComponent(labels.Value(i)) )
      return Standard_False;
  
  TDF_TagSource aTag;
  TDF_Label UpperSubL = aTag.NewChild( labels( 1 ) );
#ifdef AUTONAMING
  TCollection_ExtendedString Entry("SHUO");
  TDataStd_Name::Set(UpperSubL, TCollection_ExtendedString( Entry ));
#endif
  Handle(XCAFDoc_GraphNode) aUpperSHUO;
  aUpperSHUO = XCAFDoc_GraphNode::Set( UpperSubL, XCAFDoc::SHUORefGUID() );
  // init out argument by main upper usage SHUO
  MainSHUOAttr = aUpperSHUO;
  // add other next_usage occurrences.
  for (i = 2; i <= labels.Length(); i++) {
    TDF_Label NextSubL = aTag.NewChild( labels( i ) );
#ifdef AUTONAMING
    TCollection_ExtendedString EntrySub("SHUO-");
    EntrySub += i;
    TDataStd_Name::Set(NextSubL, TCollection_ExtendedString( EntrySub ));
#endif
    Handle(XCAFDoc_GraphNode) aNextSHUO;
    aNextSHUO = XCAFDoc_GraphNode::Set( NextSubL, XCAFDoc::SHUORefGUID() );
    // set references
    aUpperSHUO->SetChild( aNextSHUO );
    aNextSHUO->SetFather( aUpperSHUO );
    // now lets next_usage become upper_usage for next level of SHUO
    aUpperSHUO = aNextSHUO;
    UpperSubL = NextSubL;
  }
  
  return Standard_True;
}

//=======================================================================
//function : GetSHUOUpperUsage
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::GetSHUOUpperUsage (const TDF_Label& NextUsageL,
                                                       TDF_LabelSequence& aLabels)
{
  Handle(XCAFDoc_GraphNode) aNextSHUO;
  if( !GetSHUO( NextUsageL, aNextSHUO ) || aNextSHUO->NbFathers()<1 )
    return Standard_False;
  
  // get upper_usage SHAO
  for (Standard_Integer i = 1; i <= aNextSHUO->NbFathers(); i++)
    aLabels.Append( aNextSHUO->GetFather(i)->Label() );
  return Standard_True;
}

//=======================================================================
//function : GetSHUONextUsage
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::GetSHUONextUsage (const TDF_Label& UpperUsageL,
                                                      TDF_LabelSequence& aLabels)
{
  Handle(XCAFDoc_GraphNode) aUpperSHUO;
  if ( !GetSHUO( UpperUsageL, aUpperSHUO ) || aUpperSHUO->NbChildren()<1 )
    return Standard_False;
  // get upper_usage SHAO
  for (Standard_Integer i = 1; i <= aUpperSHUO->NbChildren(); i++)
    aLabels.Append( aUpperSHUO->GetChild(i)->Label() );
  return Standard_True;
}

//=======================================================================
//function : RemoveSHUO
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::RemoveSHUO (const TDF_Label& L) const
{
  L.ForgetAllAttributes (Standard_True);
  return Standard_True;
}

//=======================================================================
//function : checkForShape
//purpose  : auxilary
//=======================================================================

static Standard_Boolean checkForShape (const TopoDS_Shape& theShape,
                                       const TopoDS_Shape& theCurSh,
                                       const TDF_Label& theUserL,
                                       TDF_LabelSequence& theLabels)
{
  // the label of an assembly which contains this component
  TDF_Label aSuperUserL = theUserL.Father();
  TopLoc_Location aSupLoc, aCompLoc;
  aSupLoc = ::XCAFDoc_ShapeTool::GetLocation ( aSuperUserL );
  aCompLoc = ::XCAFDoc_ShapeTool::GetLocation ( theUserL );
  TopoDS_Shape aCopySh = theCurSh;
  aCompLoc = aCompLoc.Multiplied( theCurSh.Location() );
  aSupLoc = aSupLoc.Multiplied( aCompLoc );
  aCopySh.Location( aSupLoc );
  if ( aCopySh.IsSame( theShape ) ) {
    theLabels.Prepend( theUserL );
    return Standard_True;
  }
  // try to search deeply (upper by assmebly structure)
  TDF_LabelSequence aNewLabels;
  for (Standard_Integer j = 1; j <= theLabels.Length(); j++)
    aNewLabels.Append( theLabels.Value( j ) );
  aNewLabels.Prepend( theUserL );
  TDF_LabelSequence aUsers;
  ::XCAFDoc_ShapeTool::GetUsers( aSuperUserL, aUsers );
  for (Standard_Integer i = 1; i <= aUsers.Length(); i++)
    if ( checkForShape( theShape, aCopySh, aUsers.Value( i ), aNewLabels ) ) {
      // get solution
      theLabels = aNewLabels;
      return Standard_True;
    }
  return Standard_False;
}

//=======================================================================
//function : FindComponent
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::FindComponent (const TopoDS_Shape& theShape,
                                                  TDF_LabelSequence& theLabels) const
{
  theLabels.Clear();
  // search for a top-level shape that corresponds to this component
  TopoDS_Shape S0 = theShape;
  TopLoc_Location loc;
  S0.Location ( loc );
  TDF_Label aRefL = FindShape( S0 );
  if (aRefL.IsNull())
    return Standard_False; // cannot find top-level shape.
  
  TDF_LabelSequence aUsers;
  ::XCAFDoc_ShapeTool::GetUsers( aRefL, aUsers );
  for (Standard_Integer i = 1; i <= aUsers.Length(); i++)
    if ( checkForShape( theShape, S0, aUsers.Value( i ), theLabels ) )
      break;
  
  return (theLabels.Length() > 0);
}

//=======================================================================
//function : getShapesOfSHUO
//purpose  : auxilary
//=======================================================================

static Standard_Boolean getShapesOfSHUO (TopLoc_IndexedMapOfLocation& theaPrevLocMap,
                                         const Handle(XCAFDoc_ShapeTool)& theSTool,
                                         const TDF_Label& theSHUOlab,
                                         TopoDS_Shape& theShape)
{
  Handle(XCAFDoc_GraphNode) SHUO;
  TDF_LabelSequence aLabSeq;
  theSTool->GetSHUONextUsage( theSHUOlab, aLabSeq );
  if (aLabSeq.Length() >= 1)
    for (Standard_Integer i = 1; i <= aLabSeq.Length(); i++) {
      TDF_Label aSubCompL = aLabSeq.Value( i );
      TopLoc_Location compLoc = XCAFDoc_ShapeTool::GetLocation ( aSubCompL.Father() );
      // create new map of laocation (to not merge locations from different shapes)
      TopLoc_IndexedMapOfLocation aNewPrevLocMap;
      for (Standard_Integer m = 1; m <= theaPrevLocMap.Extent(); m++)
        aNewPrevLocMap.Add( theaPrevLocMap.FindKey( m ) );
      aNewPrevLocMap.Add( compLoc );
      // got for the new sublocations and corresponding shape
      getShapesOfSHUO( aNewPrevLocMap, theSTool, aSubCompL, theShape );
    }
  else {
    TopoDS_Shape aSHUO_NUSh = theSTool->GetShape ( theSHUOlab.Father() );
    if ( aSHUO_NUSh.IsNull() ) return Standard_False;
    // cause got shape with location already.
    TopLoc_Location nullLoc;
    aSHUO_NUSh.Location ( nullLoc );
    // multiply the locations
    Standard_Integer intMapLenght = theaPrevLocMap.Extent();
    if ( intMapLenght < 1 )
      return Standard_False; // should not be, but to avoid exception...?
    TopLoc_Location SupcompLoc;
    SupcompLoc = theaPrevLocMap.FindKey( intMapLenght );
    if (intMapLenght > 1) {
      Standard_Integer l = intMapLenght - 1;
      while (l >= 1) {
        SupcompLoc = theaPrevLocMap.FindKey( l ).Multiplied( SupcompLoc );
        l--;
      }
    }
    aSHUO_NUSh.Location( SupcompLoc );
    theShape = aSHUO_NUSh;
  }
  return (!theShape.IsNull());
}

//=======================================================================
//function : GetSHUOInstance
//purpose  : 
//=======================================================================

TopoDS_Shape XCAFDoc_ShapeTool::GetSHUOInstance (const Handle(XCAFDoc_GraphNode)& theSHUO) const
{
  TopoDS_Shape aShape;
  if (theSHUO.IsNull())
    return aShape;
  
  TDF_Label aSHUOlab = theSHUO->Label();
  // get location of the assembly
  TopLoc_Location loc = XCAFDoc_ShapeTool::GetLocation ( aSHUOlab.Father().Father() );
  // get location of the component
  TopLoc_Location compLoc = XCAFDoc_ShapeTool::GetLocation ( aSHUOlab.Father() );
  TopLoc_IndexedMapOfLocation aPrevLocMap;
  // get previous setted location 
  if ( !loc.IsIdentity() )
    aPrevLocMap.Add( loc );
  aPrevLocMap.Add( compLoc );
  // get shape by recurse method
  const Handle(XCAFDoc_ShapeTool)& STool = this;
  getShapesOfSHUO( aPrevLocMap, STool, aSHUOlab, aShape );
  
  return aShape;
}

//=======================================================================
//function : getUsersShapesOfSHUO
//purpose  : auxilary
//=======================================================================

static Standard_Boolean getUsersShapesOfSHUO (TopLoc_IndexedMapOfLocation& aPrevLocMap,
                                              const Handle(XCAFDoc_ShapeTool)& STool,
                                              const TDF_Label& aSHUOlab,
                                              const TDF_Label& theUserL,
                                              TopTools_SequenceOfShape& theSHUOShapeSeq)
{
  TopLoc_IndexedMapOfLocation aNewPrevLocMap;
  // get location of the assembly
  TopLoc_Location loc = XCAFDoc_ShapeTool::GetLocation ( theUserL.Father() );
  // get location of the component
  TopLoc_Location compLoc = XCAFDoc_ShapeTool::GetLocation ( theUserL );
  // get previous setted location 
  aNewPrevLocMap.Add( loc );
  aNewPrevLocMap.Add( compLoc );
  Standard_Integer i;
  for (i = 1; i <= aPrevLocMap.Extent(); i++)
    aNewPrevLocMap.Add( aPrevLocMap.FindKey(i) );
  TDF_Label L = theUserL.Father();
  TDF_LabelSequence usersLab;
  ::XCAFDoc_ShapeTool::GetUsers( L, usersLab );
  if (usersLab.Length() == 0) {
    TopoDS_Shape aShape;
    getShapesOfSHUO( aNewPrevLocMap, STool, aSHUOlab, aShape );
    if (!aShape.IsNull()) {
      theSHUOShapeSeq.Append(aShape);
      return Standard_True;
    }
  }
  // now iterates on users of this assembly as component
  for ( i = 1; i <= usersLab.Length(); i++ ) {
    TDF_Label aNewUserL = usersLab.Value(i);
    getUsersShapesOfSHUO( aNewPrevLocMap, STool, aSHUOlab, aNewUserL, theSHUOShapeSeq );
  }
  
  return (theSHUOShapeSeq.Length() > 1);
}

//=======================================================================
//function : GetAllSHUOInstances
//purpose  : auxilary
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::GetAllSHUOInstances (const Handle(XCAFDoc_GraphNode)& theSHUO,
                                                         TopTools_SequenceOfShape& theSHUOShapeSeq) const
{
  if (theSHUO.IsNull())
    return Standard_False;

  TDF_Label aSHUOlab = theSHUO->Label();
  TopLoc_IndexedMapOfLocation aPrevLocMap;
  // get location of the assembly
  TopLoc_Location loc = XCAFDoc_ShapeTool::GetLocation ( aSHUOlab.Father().Father() );
  // get location of the component
  TopLoc_Location compLoc = XCAFDoc_ShapeTool::GetLocation ( aSHUOlab.Father() );
  // get previous setted location 
  if ( !loc.IsIdentity() )
    aPrevLocMap.Add( loc );
  aPrevLocMap.Add( compLoc );
  // get label of assembly
  TDF_Label L = aSHUOlab.Father().Father();
  TDF_LabelSequence usersLab;
  ::XCAFDoc_ShapeTool::GetUsers( L, usersLab );
  TopoDS_Shape aShape;
  const Handle(XCAFDoc_ShapeTool)& STool = this;
  if (usersLab.Length() == 0) {
    getShapesOfSHUO( aPrevLocMap, STool, aSHUOlab, aShape );
    if (!aShape.IsNull()) {
      theSHUOShapeSeq.Append(aShape);
      return Standard_True;
    }
  }
  // now iterates on users of this assembly as component
  for (Standard_Integer i = 1; i <= usersLab.Length(); i++) {
    TDF_Label aUserL = usersLab.Value(i);
    getUsersShapesOfSHUO( aPrevLocMap, STool, aSHUOlab, aUserL, theSHUOShapeSeq );
  }
  
  return (theSHUOShapeSeq.Length() > 1);
}

//=======================================================================
//function : SetInstanceSHUO
//purpose  : 
//=======================================================================

Handle(XCAFDoc_GraphNode) XCAFDoc_ShapeTool::SetInstanceSHUO (const TopoDS_Shape& theShape) const
{
  Handle(XCAFDoc_GraphNode) SHUO;
  TDF_LabelSequence aLabels;
  if ( FindComponent( theShape, aLabels ) )
    // set shuo structure on labels of component-assembly structure
    SetSHUO( aLabels, SHUO );
  return SHUO;
}

//=======================================================================
//function : FindSHUO
//purpose  : 
//=======================================================================

Standard_Boolean XCAFDoc_ShapeTool::FindSHUO (const TDF_LabelSequence& theLabels,
                                              Handle(XCAFDoc_GraphNode)& theSHUOAttr)
{
  TDF_AttributeSequence SHUOAttrs;
  TDF_Label aCompLabel = theLabels.Value(1);
  if (! ::XCAFDoc_ShapeTool::GetAllComponentSHUO( aCompLabel, SHUOAttrs ) )
    return Standard_False;
  // WARNING: manage that each SHUO upper_usage have only one SHUO next_usage
  for (Standard_Integer i = 1; i <= SHUOAttrs.Length(); i++) {
    TDF_LabelSequence aCondidate;
    Handle(XCAFDoc_GraphNode) anSHUO = Handle(XCAFDoc_GraphNode)::DownCast(SHUOAttrs.Value(i));
    aCondidate.Append( anSHUO->Label().Father() );
    while (anSHUO->NbChildren()) {
      anSHUO = anSHUO->GetChild( 1 );
      aCondidate.Append( anSHUO->Label().Father() );
    }
    // check the label sequences
    Standard_Boolean isEqual = Standard_True;
    if (theLabels.Length() != aCondidate.Length())
      isEqual = Standard_False;
    else
      for (Standard_Integer li = 1; li <= theLabels.Length(); li++)
        if ( theLabels.Value(li) != aCondidate.Value(li) ) {
          isEqual = Standard_False;
          break;
        }
    if (!isEqual)
      continue;
      
    theSHUOAttr = Handle(XCAFDoc_GraphNode)::DownCast(SHUOAttrs.Value(i));
    break;
  }
  return ( !theSHUOAttr.IsNull() );
}