b39e3b0b5f8358bbb4787592f0e0c2aa51a88365
[occt.git] / src / XCAFDoc / XCAFDoc_ShapeTool.cxx
1 // Created on: 2000-08-03
2 // Created by: data exchange team
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 <gp_Pnt.hxx>
19 #include <gp_Trsf.hxx>
20 #include <Standard_GUID.hxx>
21 #include <Standard_Type.hxx>
22 #include <TCollection_AsciiString.hxx>
23 #include <TCollection_ExtendedString.hxx>
24 #include <TCollection_HAsciiString.hxx>
25 #include <TColStd_SequenceOfHAsciiString.hxx>
26 #include <TDataStd_ChildNodeIterator.hxx>
27 #include <TDataStd_Name.hxx>
28 #include <TDataStd_TreeNode.hxx>
29 #include <TDataStd_UAttribute.hxx>
30 #include <TDF_Attribute.hxx>
31 #include <TDF_ChildIDIterator.hxx>
32 #include <TDF_ChildIterator.hxx>
33 #include <TDF_Label.hxx>
34 #include <TDF_LabelMap.hxx>
35 #include <TDF_LabelSequence.hxx>
36 #include <TDF_MapIteratorOfLabelMap.hxx>
37 #include <TDF_RelocationTable.hxx>
38 #include <TDF_Tool.hxx>
39 #include <TDocStd_Document.hxx>
40 #include <TNaming_Builder.hxx>
41 #include <TNaming_NamedShape.hxx>
42 #include <TNaming_Tool.hxx>
43 #include <TopLoc_IndexedMapOfLocation.hxx>
44 #include <TopLoc_Location.hxx>
45 #include <TopoDS_Compound.hxx>
46 #include <TopoDS_Iterator.hxx>
47 #include <TopoDS_Shape.hxx>
48 #include <TopTools_ListOfShape.hxx>
49 #include <XCAFDoc.hxx>
50 #include <XCAFDoc_GraphNode.hxx>
51 #include <XCAFDoc_Location.hxx>
52 #include <XCAFDoc_ShapeMapTool.hxx>
53 #include <XCAFDoc_ShapeTool.hxx>
54
55 IMPLEMENT_STANDARD_RTTIEXT(XCAFDoc_ShapeTool,TDF_Attribute)
56
57 static Standard_Boolean theAutoNaming = Standard_True;
58
59 // attribute methods //////////////////////////////////////////////////
60
61 //=======================================================================
62 //function : GetID
63 //purpose  : 
64 //=======================================================================
65
66 const Standard_GUID& XCAFDoc_ShapeTool::GetID() 
67 {
68   static Standard_GUID ShapeToolID ("efd212ee-6dfd-11d4-b9c8-0060b0ee281b");
69   return ShapeToolID; 
70 }
71
72
73 //=======================================================================
74 //function : Set
75 //purpose  : 
76 //=======================================================================
77
78 Handle(XCAFDoc_ShapeTool) XCAFDoc_ShapeTool::Set(const TDF_Label& L) 
79 {
80   Handle(XCAFDoc_ShapeTool) A;
81   if (!L.FindAttribute (XCAFDoc_ShapeTool::GetID(), A)) {
82     A = new XCAFDoc_ShapeTool ();
83     L.AddAttribute(A);
84   }
85   A->Init();
86   return A;
87 }
88
89
90 //=======================================================================
91 //function : Constructor
92 //purpose  : 
93 //=======================================================================
94
95 XCAFDoc_ShapeTool::XCAFDoc_ShapeTool()
96 {
97   hasSimpleShapes = Standard_False;
98 }
99
100
101 //=======================================================================
102 //function : ID
103 //purpose  : 
104 //=======================================================================
105
106 const Standard_GUID& XCAFDoc_ShapeTool::ID() const
107 {
108   return GetID();
109 }
110
111 //=======================================================================
112 //function : Restore
113 //purpose  : 
114 //=======================================================================
115
116 void XCAFDoc_ShapeTool::Restore(const Handle(TDF_Attribute)& /*with*/) 
117 {
118 }
119
120 //=======================================================================
121 //function : NewEmpty
122 //purpose  : 
123 //=======================================================================
124
125 Handle(TDF_Attribute) XCAFDoc_ShapeTool::NewEmpty() const
126 {
127   return new XCAFDoc_ShapeTool;
128 }
129
130 //=======================================================================
131 //function : Paste
132 //purpose  : 
133 //=======================================================================
134
135 void XCAFDoc_ShapeTool::Paste (const Handle(TDF_Attribute)& /*into*/,
136                                const Handle(TDF_RelocationTable)& /*RT*/) const
137 {
138 }
139
140 // Auxiliary methods //////////////////////////////////////////////////
141
142 //=======================================================================
143 //function : SetLabelNameByLink
144 //purpose  : 
145 //=======================================================================
146 static void SetLabelNameByLink(const TDF_Label L) 
147 {
148   Handle(TDataStd_TreeNode) Node;
149   if (! L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) ||
150       ! Node->HasFather()) {
151 #ifdef OCCT_DEBUG
152     cout<<"Error: XCAFDoc_ShapeTool, SetLabelNameByLink(): NO NODE"<<endl;
153 #endif
154     return;
155   }
156   TCollection_AsciiString Entry;
157   TDF_Tool::Entry ( Node->Father()->Label(), Entry );
158   Entry.Insert(1, "=>[");
159   Entry += "]";
160
161   TDataStd_Name::Set(L, TCollection_ExtendedString( Entry ));
162 }
163
164
165 //=======================================================================
166 //function : SetLabelNameByShape
167 //purpose  : 
168 //=======================================================================
169 static void SetLabelNameByShape(const TDF_Label L) 
170 {
171   TopoDS_Shape S;
172   if (XCAFDoc_ShapeTool::GetShape(L, S) &&
173       ! L.IsAttribute(TDataStd_Name::GetID()) ) {
174     Standard_SStream Stream;
175 //    TopAbs_ShapeEnum Type = S.ShapeType();
176 //    if (Type == TopAbs_COMPOUND) Stream<<"ASSEMBLY";
177 //    else 
178     TopAbs::Print(S.ShapeType(), Stream);
179     TCollection_AsciiString aName (Stream.str().c_str());
180     TDataStd_Name::Set(L, TCollection_ExtendedString(aName));
181   }
182 }
183
184
185 //=======================================================================
186 //function : SearchUsingMap
187 //purpose  : 
188 //=======================================================================
189
190 Standard_Boolean XCAFDoc_ShapeTool::SearchUsingMap(const TopoDS_Shape &S, TDF_Label &L,
191                                                    const Standard_Boolean findWithoutLoc,
192                                                    const Standard_Boolean findSubShape) const
193 {
194
195   if(myShapeLabels.IsBound(S)) {
196     L = myShapeLabels.Find(S);
197     return Standard_True;
198   }
199   TopoDS_Shape S0 = S;
200   TopLoc_Location loc;
201   S0.Location(loc);
202   if(myShapeLabels.IsBound(S0)) {
203     TDF_Label L1 = myShapeLabels.Find(S0);
204     TDF_LabelSequence Labels;
205     if(GetUsers(L1, Labels, Standard_True)) {
206       for(Standard_Integer i=1; i<=Labels.Length(); i++) {
207         TopoDS_Shape c = GetShape(Labels.Value(i));
208         if(c.IsSame(S)) {
209           L = Labels.Value(i);
210           return Standard_True;
211         }
212       }
213     }
214     if(findWithoutLoc) {
215       L = L1;
216       return Standard_True;
217     }
218   }
219
220   if(hasSimpleShapes) {
221     if(mySimpleShapes.IsBound(S)) {
222       L = mySimpleShapes.Find(S);
223       return Standard_True;
224     }
225     if(mySimpleShapes.IsBound(S0)) {
226       L = mySimpleShapes.Find(S0);
227       return Standard_True;
228     }
229   }
230   // search subshapes
231   if(!findSubShape) return Standard_False;
232   TDF_Label mainL = FindMainShapeUsingMap(S);
233   if(mainL.IsNull()) return Standard_False;
234   L = AddSubShape(mainL,S);
235   return !L.IsNull();//Standard_True;
236 }
237
238
239 //=======================================================================
240 //function : Search
241 //purpose  : 
242 //=======================================================================
243
244 Standard_Boolean XCAFDoc_ShapeTool::Search (const TopoDS_Shape &S, 
245                                          TDF_Label &L,
246                                          const Standard_Boolean findInstance,
247                                          const Standard_Boolean findComponent,
248                                          const Standard_Boolean findSubShape) const
249 {
250   // search among shapes
251   Standard_Boolean isLocated = ! S.Location().IsIdentity();
252   
253   if ( isLocated ) {
254     // try to find top-level instance
255     if ( findInstance && FindShape ( S, L, Standard_True ) )
256       return Standard_True;
257     // try to find component of assembly
258     if ( findComponent ) {
259       TDF_LabelSequence labels;
260       GetShapes ( labels );
261       for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
262         if ( ! IsAssembly ( labels.Value(i) ) ) continue;
263         TDF_LabelSequence comp;
264         GetComponents ( labels.Value(i), comp );
265         for ( Standard_Integer j=1; j <= comp.Length(); j++ ) {
266           TopoDS_Shape c = GetShape ( comp.Value(j) );
267           if ( c.IsSame ( S ) ) {
268             L = comp.Value(j);
269             return Standard_True;
270           }
271         }
272       }
273     }
274   }
275   // try to find top-level simple shape
276   if ( FindShape ( S, L, Standard_False ) ) return Standard_True;
277   
278   // search subshapes
279   if ( ! findSubShape ) return Standard_False;
280   TDF_Label mainL = FindMainShape ( S );
281   if ( mainL.IsNull() ) return Standard_False;
282   L = AddSubShape ( mainL, S );
283   return !L.IsNull();//Standard_True;
284 }
285
286 //=======================================================================
287 //function : FindShape
288 //purpose  : 
289 //=======================================================================
290
291 Standard_Boolean XCAFDoc_ShapeTool::FindShape (const TopoDS_Shape& S, 
292                                                TDF_Label& L,
293                                                const Standard_Boolean findInstance) const
294 {
295   // search for null-located shape
296   TopoDS_Shape S0 = S;
297   if ( ! findInstance ) {
298     TopLoc_Location loc;
299     S0.Location ( loc );
300   }
301
302   // this code is used instead of the following for performance reasons
303   if (TNaming_Tool::HasLabel(Label(), S0)) {
304     int TransDef = 0;
305     L = TNaming_Tool::Label(Label(), S0, TransDef);
306     return Standard_True;
307   }
308 /*
309   TDF_ChildIDIterator it(myLabel,TNaming_NamedShape::GetID());
310   for (; it.More(); it.Next()) {
311     TDF_Label aLabel = it.Value()->Label();
312     Handle(TNaming_NamedShape) NS;
313     if ( aLabel.FindAttribute(TNaming_NamedShape::GetID(), NS) &&
314          S0.IsSame ( TNaming_Tool::GetShape(NS) ) ) {
315       L = aLabel;
316       return Standard_True;
317     }
318   }
319 */
320   return Standard_False;
321 }
322
323 //=======================================================================
324 //function : FindShape
325 //purpose  : 
326 //=======================================================================
327
328 TDF_Label XCAFDoc_ShapeTool::FindShape (const TopoDS_Shape& S,
329                                      const Standard_Boolean findInstance) const
330 {
331   TDF_Label L;
332   if (FindShape(S, L, findInstance))
333     return L;
334   return TDF_Label();
335 }
336
337 //=======================================================================
338 //function : GetShape
339 //purpose  : 
340 //=======================================================================
341
342 Standard_Boolean XCAFDoc_ShapeTool::GetShape (const TDF_Label& L, TopoDS_Shape& S) 
343 {
344   Handle(XCAFDoc_Location) LocationAttribute;
345
346   if(IsExternRef(L)) {
347     TopoDS_Compound EmptyComp;
348     BRep_Builder B;
349     B.MakeCompound(EmptyComp);
350     S = EmptyComp;
351   }
352
353   // for instance, get referred shape
354   Handle(TDataStd_TreeNode) Node;
355   if ( L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) && Node->HasFather() && 
356        L.FindAttribute(XCAFDoc_Location::GetID(), LocationAttribute)) {
357     if ( ! GetShape(Node->Father()->Label(), S) ) return Standard_False;
358     S.Move ( LocationAttribute->Get() );
359     return Standard_True;
360   }
361
362   // else just return shape on this label
363   Handle(TNaming_NamedShape) NS;
364   if ( ! L.FindAttribute(TNaming_NamedShape::GetID(), NS) ) return Standard_False;
365   S = TNaming_Tool::GetShape(NS);
366   return Standard_True;
367 }
368
369 //=======================================================================
370 //function : GetShape
371 //purpose  : 
372 //=======================================================================
373
374 TopoDS_Shape XCAFDoc_ShapeTool::GetShape(const TDF_Label& L) 
375 {
376   TopoDS_Shape aShape;
377   GetShape(L,aShape);
378   return aShape;
379 }
380
381 //=======================================================================
382 //function : NewShape
383 //purpose  : 
384 //=======================================================================
385
386 TDF_Label XCAFDoc_ShapeTool::NewShape() const
387 {
388   TopoDS_Compound aShape;
389   BRep_Builder tdsB;
390   tdsB.MakeCompound ( aShape );
391
392   TDF_TagSource aTag;
393   TDF_Label aLabel = aTag.NewChild(Label());
394   
395   TNaming_Builder tnBuild(aLabel);
396   tnBuild.Generated(aShape);
397   
398   return aLabel;
399 }
400
401 //=======================================================================
402 //function : SetShape
403 //purpose  : 
404 //=======================================================================
405
406 void XCAFDoc_ShapeTool::SetShape (const TDF_Label& L, const TopoDS_Shape& S)
407 {
408   TNaming_Builder tnBuild(L);
409   tnBuild.Generated(S);
410   Handle(XCAFDoc_ShapeMapTool) A = XCAFDoc_ShapeMapTool::Set(L);
411 //  if ( ! L.FindAttribute(XCAFDoc_ShapeMapTool::GetID(), A) ) {
412 //    A = XCAFDoc_ShapeMapTool::Set(L);
413 //    L.AddAttribute(A);
414 //  }
415   A->SetShape(S);
416
417   if(!myShapeLabels.IsBound(S)) {
418     myShapeLabels.Bind(S,L);
419   }
420 }
421
422 //=======================================================================
423 //function : MakeReference
424 //purpose  : 
425 //=======================================================================
426
427 void XCAFDoc_ShapeTool::MakeReference (const TDF_Label &L, 
428                                     const TDF_Label &refL,
429                                     const TopLoc_Location &loc)
430 {
431   // store location
432   XCAFDoc_Location::Set(L, loc);
433     
434     // set reference
435   Handle(TDataStd_TreeNode) refNode, mainNode;
436   mainNode = TDataStd_TreeNode::Set ( refL, XCAFDoc::ShapeRefGUID() );
437   refNode  = TDataStd_TreeNode::Set ( L,    XCAFDoc::ShapeRefGUID() );
438   refNode->Remove(); // abv: fix against bug in TreeNode::Append()
439   mainNode->Append(refNode);
440
441   if (theAutoNaming)
442     SetLabelNameByLink(L);
443 }
444
445 //=======================================================================
446 //function : addShape
447 //purpose  : private
448 //=======================================================================
449
450 TDF_Label XCAFDoc_ShapeTool::addShape (const TopoDS_Shape& S, const Standard_Boolean makeAssembly)
451 {
452   TDF_Label ShapeLabel;
453   TDF_TagSource aTag;
454
455   // search if the shape already exists (with the same location)
456   if ( S.IsNull() || FindShape ( S, ShapeLabel, Standard_True ) ) return ShapeLabel;
457   
458   // else add a new label
459   ShapeLabel = aTag.NewChild(Label());
460   
461   // if shape has location, make a reference to the same shape without location
462   if ( ! S.Location().IsIdentity() /*&& FindShape ( S, L )*/ ) {
463     TopoDS_Shape S0 = S;
464     TopLoc_Location loc;
465     S0.Location ( loc );
466     TDF_Label L = addShape ( S0, makeAssembly );
467     MakeReference ( ShapeLabel, L, S.Location() );
468     return ShapeLabel;
469   }
470   
471   // else add a shape to a label
472   TNaming_Builder tnBuild(ShapeLabel);
473   tnBuild.Generated(S);
474   
475   Handle(XCAFDoc_ShapeMapTool) A = XCAFDoc_ShapeMapTool::Set(ShapeLabel);
476 //  if ( ! ShapeLabel.FindAttribute(XCAFDoc_ShapeMapTool::GetID(), A) ) {
477 //    A = XCAFDoc_ShapeMapTool::Set(ShapeLabel);
478 //    ShapeLabel.AddAttribute(A);
479 //  }
480   A->SetShape(S);
481   
482   if (theAutoNaming)
483     SetLabelNameByShape(ShapeLabel);
484
485   // if shape is Compound and flag is set, create assembly
486   if ( makeAssembly && S.ShapeType() == TopAbs_COMPOUND ) {
487     // mark assembly by assigning UAttribute
488     Handle(TDataStd_UAttribute) Uattr;
489     Uattr = TDataStd_UAttribute::Set ( ShapeLabel, XCAFDoc::AssemblyGUID() );
490     if (theAutoNaming)
491       TDataStd_Name::Set(ShapeLabel, TCollection_ExtendedString("ASSEMBLY"));
492
493     // iterate on components
494     TopoDS_Iterator Iterator(S);
495     for (; Iterator.More(); Iterator.Next()) {
496       // get label for component`s shape
497       TopoDS_Shape Scomp = Iterator.Value(), S0 = Scomp;
498       TopLoc_Location loc;
499       S0.Location ( loc );
500       TDF_Label compL = addShape ( S0, makeAssembly );
501       
502       // add a component as reference
503       TDF_Label RefLabel = aTag.NewChild(ShapeLabel);
504       MakeReference ( RefLabel, compL, Scomp.Location() );
505     }
506   }
507   
508   if(!IsAssembly(ShapeLabel)) {
509     //const TopTools_IndexedMapOfShape tmpMap = A->GetMap();
510     //for(Standard_Integer i=1; i<=tmpMap.Extent(); i++)
511     //mySubShapes.Bind(tmpMap.FindKey(i),ShapeLabel);
512     for(Standard_Integer i=1; i<=A->GetMap().Extent(); i++)
513     {
514       TopoDS_Shape aSh = A->GetMap().FindKey(i);
515       mySubShapes.Bind(aSh,ShapeLabel);
516     }
517     //mySubShapes.Bind(ShapeLabel,A->GetMap());
518   }
519
520   return ShapeLabel;
521 }
522
523
524 //=======================================================================
525 //function : prepareAssembly
526 //purpose  : auxilary
527 //=======================================================================
528 static Standard_Boolean prepareAssembly (const TopoDS_Shape& theShape,
529                                          TopoDS_Shape& theOUTShape)
530 {
531   // iterate on components
532   theOUTShape = theShape;
533   if (theShape.ShapeType() == TopAbs_COMPOUND) {
534     BRep_Builder B;
535     // check if shape if frosen
536     if (!theOUTShape.Free())
537       theOUTShape.Free(Standard_True);
538     
539     TopTools_SequenceOfShape aSubShapeSeq;
540     TopoDS_Iterator Iterator(theShape);
541     for (; Iterator.More(); Iterator.Next())
542       aSubShapeSeq.Append(Iterator.Value());
543     for (Standard_Integer i = 1; i <= aSubShapeSeq.Length(); i++) {
544       TopoDS_Shape Scomp = aSubShapeSeq.Value(i);
545       TopoDS_Shape aNewScomp;
546       B.Remove(theOUTShape, Scomp);
547       prepareAssembly( Scomp, aNewScomp );
548       TopLoc_Location aLoc;
549       aLoc = aNewScomp.Location();
550       if ( aLoc.IsIdentity() ) {
551         // create an "empty" location
552         gp_Trsf aTrsf;
553         aTrsf.SetScale(gp_Pnt(0,0,0), 1);
554         aLoc = TopLoc_Location( aTrsf );
555         aNewScomp.Location( aLoc );
556       }
557       B.Add(theOUTShape, aNewScomp);
558     }
559   }
560   return Standard_True;
561 }
562
563
564 //=======================================================================
565 //function : AddShape
566 //purpose  : 
567 //=======================================================================
568
569 TDF_Label XCAFDoc_ShapeTool::AddShape (const TopoDS_Shape& theShape,
570                                        const Standard_Boolean makeAssembly,
571                                        const Standard_Boolean makePrepare)
572 {
573   // PTV 17.02.2003 to avoid components without location.
574   TopoDS_Shape S = theShape;
575   if ( makePrepare && makeAssembly && S.ShapeType() == TopAbs_COMPOUND )
576     prepareAssembly( theShape, S ); // OCC1669
577   
578   TDF_Label L = addShape(S,makeAssembly);
579
580   if(!myShapeLabels.IsBound(S)) {
581     myShapeLabels.Bind(S,L);
582   }
583
584   return L;
585
586   //return addShape( S, makeAssembly );
587 }
588
589 //=======================================================================
590 //function : RemoveShape
591 //purpose  : 
592 //=======================================================================
593
594 Standard_Boolean XCAFDoc_ShapeTool::RemoveShape (const TDF_Label& L,
595                                                  const Standard_Boolean removeCompletely) const
596 {
597   if ( ! IsTopLevel ( L ) || ! IsFree ( L ) ) return Standard_False;
598
599   Handle(TDataStd_TreeNode) aNode;
600   TDF_Label aLabel;
601   if (removeCompletely &&
602       L.FindAttribute (XCAFDoc::ShapeRefGUID(), aNode) &&
603       aNode->HasFather() &&
604       L.IsAttribute (XCAFDoc_Location::GetID()))
605   {
606     aLabel = aNode->Father()->Label();
607   }
608
609   L.ForgetAllAttributes (Standard_True);
610
611   if (removeCompletely && !aLabel.IsNull())
612   {
613     return RemoveShape(aLabel);
614   }
615   return Standard_True;
616 }
617
618
619 //=======================================================================
620 //function : Init
621 //purpose  : 
622 //=======================================================================
623
624 void XCAFDoc_ShapeTool::Init()
625 {
626   hasSimpleShapes = Standard_False;
627 }
628
629
630 //=======================================================================
631 //function : SetAutoNaming
632 //purpose  : 
633 //=======================================================================
634
635 void XCAFDoc_ShapeTool::SetAutoNaming (const Standard_Boolean V)
636 {
637   theAutoNaming = V;
638 }
639
640
641 //=======================================================================
642 //function : AutoNaming
643 //purpose  : 
644 //=======================================================================
645
646 Standard_Boolean XCAFDoc_ShapeTool::AutoNaming()
647 {
648   return theAutoNaming;
649 }
650
651
652 //=======================================================================
653 //function : ComputeShapes
654 //purpose  : 
655 //=======================================================================
656
657 void XCAFDoc_ShapeTool::ComputeShapes(const TDF_Label& L)
658 {
659   TDF_ChildIterator it(L); 
660   for(; it.More(); it.Next()) {
661     TDF_Label L1 = it.Value();
662     TopoDS_Shape S;
663     if(GetShape(L1,S)) {
664       if(!myShapeLabels.IsBound(S)) {
665         mySimpleShapes.Bind(S,L1);
666       }
667     }
668     ComputeShapes(L1);
669   }
670 }
671
672
673 //=======================================================================
674 //function : ComputeSimpleShapes
675 //purpose  : 
676 //=======================================================================
677
678 void XCAFDoc_ShapeTool::ComputeSimpleShapes()
679 {
680   ComputeShapes(Label());
681   hasSimpleShapes = Standard_True;
682 }
683
684
685 //=======================================================================
686 //function : GetShapes
687 //purpose  : 
688 //=======================================================================
689
690 void XCAFDoc_ShapeTool::GetShapes(TDF_LabelSequence& Labels) const
691 {
692   Labels.Clear();
693
694   TDF_ChildIterator it(Label()); 
695   for (; it.More(); it.Next()) {
696     TDF_Label L = it.Value();
697     TopoDS_Shape S;
698     if ( GetShape ( L, S ) ) Labels.Append ( L );
699   }
700 }
701
702
703 //=======================================================================
704 //function : GetFreeShapes
705 //purpose  : 
706 //=======================================================================
707
708 void XCAFDoc_ShapeTool::GetFreeShapes (TDF_LabelSequence& FreeLabels) const
709 {
710   FreeLabels.Clear();
711
712   TDF_ChildIterator it(Label());
713   for (; it.More(); it.Next()) {
714     TDF_Label L = it.Value();
715     TopoDS_Shape S;
716     if ( GetShape ( L, S ) && IsFree ( L ) ) FreeLabels.Append ( L );
717   }
718 }
719
720 //=======================================================================
721 //function : IsTopLevel
722 //purpose  : 
723 //=======================================================================
724
725 Standard_Boolean XCAFDoc_ShapeTool::IsTopLevel (const TDF_Label& L) const
726 {
727   return L.Father() == Label();
728 }
729
730 //=======================================================================
731 //function : IsShape
732 //purpose  : 
733 //=======================================================================
734
735 Standard_Boolean XCAFDoc_ShapeTool::IsShape (const TDF_Label& L) 
736 {
737   return IsSimpleShape ( L ) || IsAssembly ( L ) || IsReference ( L );
738 }
739
740 //=======================================================================
741 //function : IsSimpleShape
742 //purpose  : 
743 //=======================================================================
744
745 Standard_Boolean XCAFDoc_ShapeTool::IsSimpleShape (const TDF_Label& L) 
746 {
747   Handle(TNaming_NamedShape) NS;
748   return L.FindAttribute ( TNaming_NamedShape::GetID(), NS ) &&
749          ! IsAssembly ( L ) && ! IsReference ( L );
750 }
751
752 //=======================================================================
753 //function : IsReference
754 //purpose  : 
755 //=======================================================================
756
757 Standard_Boolean XCAFDoc_ShapeTool::IsReference (const TDF_Label& L)
758 {
759   Handle(TDataStd_TreeNode) Node;
760   return L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) && Node->HasFather();
761 }
762
763 //=======================================================================
764 //function : IsAssembly
765 //purpose  : 
766 //=======================================================================
767
768 Standard_Boolean XCAFDoc_ShapeTool::IsAssembly (const TDF_Label& L) 
769 {
770   Handle(TDataStd_UAttribute) Uattr;
771   return L.FindAttribute(XCAFDoc::AssemblyGUID(), Uattr);
772 }
773
774 //=======================================================================
775 //function : IsComponent
776 //purpose  : 
777 //=======================================================================
778
779 Standard_Boolean XCAFDoc_ShapeTool::IsComponent (const TDF_Label& L)
780 {
781   return IsReference ( L ) && IsAssembly ( L.Father() );
782 }
783
784 //=======================================================================
785 //function : IsCompound
786 //purpose  : 
787 //=======================================================================
788
789 Standard_Boolean XCAFDoc_ShapeTool::IsCompound (const TDF_Label& L) 
790 {
791   Handle(TDataStd_Name) Name;
792   if (L.FindAttribute(TDataStd_Name::GetID(),Name)) {
793     TCollection_ExtendedString estr1 = Name->Get();
794     TCollection_ExtendedString estr2("COMPOUND");
795     if(estr1==estr2) {
796       return Standard_True;
797     }
798   }
799   return Standard_False;
800 }
801
802 //=======================================================================
803 //function : IsSubShape
804 //purpose  : 
805 //=======================================================================
806
807 Standard_Boolean XCAFDoc_ShapeTool::IsSubShape (const TDF_Label& L)
808 {
809   return IsSimpleShape ( L ) && IsShape ( L.Father() );
810 }
811
812 //=======================================================================
813 //function : IsFree
814 //purpose  : 
815 //=======================================================================
816
817 Standard_Boolean XCAFDoc_ShapeTool::IsFree (const TDF_Label& L) 
818 {
819   Handle(TDataStd_TreeNode) Node;
820   if ( ! L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) || 
821        ! Node->HasFirst() ) return Standard_True;
822
823   return Standard_False;
824 }
825
826 //=======================================================================
827 //function : GetUsers
828 //purpose  : Returns number of users (0 if shape is free)
829 //=======================================================================
830
831 Standard_Integer XCAFDoc_ShapeTool::GetUsers (const TDF_Label& L, 
832                                               TDF_LabelSequence& Labels,
833                                               const Standard_Boolean getsubchilds)
834 {
835   Standard_Integer NbUsers=0;
836   Handle(TDataStd_TreeNode) Node  ;
837
838   if ( ! L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node) ) return NbUsers;
839   
840   Node = Node->First();
841   while ( ! Node.IsNull() ) {
842     
843     if ( getsubchilds ) {
844       TDF_Label underL = Node->Label().Father();
845       NbUsers += GetUsers ( underL, Labels, getsubchilds );
846     }
847     
848     Labels.Append(Node->Label());
849     Node = Node->Next();
850     NbUsers++;
851   }
852   return NbUsers;
853 }
854   
855 //=======================================================================
856 //function : NbComponents
857 //purpose  : 
858 //=======================================================================
859
860 Standard_Integer XCAFDoc_ShapeTool::NbComponents (const TDF_Label& L,
861                                                   const Standard_Boolean getsubchilds) 
862 {
863   TDF_LabelSequence subLabels;
864   GetComponents (L, subLabels, getsubchilds);
865   return subLabels.Length();
866 }
867
868 //=======================================================================
869 //function : GetComponents
870 //purpose  : 
871 //=======================================================================
872
873 Standard_Boolean XCAFDoc_ShapeTool::GetComponents (const TDF_Label& L, TDF_LabelSequence& Labels,
874                                                    const Standard_Boolean getsubchilds) 
875 {
876   if ( ! IsAssembly(L) ) return Standard_False;
877   
878   TDF_ChildIterator It(L);
879   for (; It.More(); It.Next() ) {
880     TDF_Label comp = It.Value();
881     if ( IsComponent ( comp ) ) {
882       if ( getsubchilds ) {
883         TDF_Label underL;
884         if ( GetReferredShape ( comp, underL ) )
885           GetComponents ( underL, Labels, getsubchilds);
886       }
887       Labels.Append ( comp );
888     }
889   }
890   return Standard_True;
891 }
892
893 //=======================================================================
894 //function : GetLocation
895 //purpose  : 
896 //=======================================================================
897
898 TopLoc_Location XCAFDoc_ShapeTool::GetLocation (const TDF_Label& L)
899 {
900   Handle(XCAFDoc_Location) LocationAttribute;
901   if (L.FindAttribute(XCAFDoc_Location::GetID(), LocationAttribute)) 
902     return LocationAttribute->Get();
903   
904   Handle(TNaming_NamedShape) NS;
905   TopoDS_Shape S;
906   if ( L.FindAttribute ( TNaming_NamedShape::GetID(), NS ) ) {
907     S = TNaming_Tool::GetShape(NS);
908   }
909   return S.Location();
910 }
911
912 //=======================================================================
913 //function : GetReferredShape
914 //purpose  : 
915 //=======================================================================
916
917 Standard_Boolean XCAFDoc_ShapeTool::GetReferredShape (const TDF_Label& L, 
918                                                       TDF_Label& Label)
919 {
920   if ( ! IsReference(L) ) return Standard_False;
921   
922   Handle (TDataStd_TreeNode) Node;
923   L.FindAttribute(XCAFDoc::ShapeRefGUID(), Node);
924   Label = Node->Father()->Label();
925   return Standard_True;
926 }
927
928 //=======================================================================
929 //function : AddComponent
930 //purpose  : 
931 //=======================================================================
932
933 TDF_Label XCAFDoc_ShapeTool::AddComponent (const TDF_Label& assembly, 
934                                            const TDF_Label& compL, 
935                                            const TopLoc_Location &Loc) const
936 {
937   TDF_Label L;
938   
939   // check that shape is assembly
940   if ( ! IsAssembly(assembly) ) {
941     // if it is simple shape, make it assembly
942     if ( IsSimpleShape(assembly) ) 
943       TDataStd_UAttribute::Set ( assembly, XCAFDoc::AssemblyGUID() );
944     else return L;
945   }
946   
947   // add a component as reference
948   TDF_TagSource aTag;
949   L = aTag.NewChild(assembly);
950   MakeReference ( L, compL, Loc );
951
952   return L;
953 }
954
955 //=======================================================================
956 //function : AddComponent
957 //purpose  : 
958 //=======================================================================
959
960 TDF_Label XCAFDoc_ShapeTool::AddComponent (const TDF_Label& assembly, 
961                                            const TopoDS_Shape& comp,
962                                            const Standard_Boolean expand)
963 {
964   // get label for component`s shape
965   TopoDS_Shape S0 = comp;
966   TopLoc_Location loc;
967   S0.Location ( loc );
968   TDF_Label compL;
969   compL = AddShape ( S0, expand );
970   
971   // add component by its label
972   return AddComponent ( assembly, compL, comp.Location() );
973 }
974
975 //=======================================================================
976 //function : RemoveComponent
977 //purpose  : 
978 //=======================================================================
979
980 void XCAFDoc_ShapeTool::RemoveComponent (const TDF_Label& comp) const
981 {
982   if ( IsComponent(comp) )
983   {
984     comp.ForgetAllAttributes();
985   }
986 }
987
988 //=======================================================================
989 //function : UpdateAssemblies
990 //purpose  : 
991 //=======================================================================
992
993 void XCAFDoc_ShapeTool::UpdateAssemblies()
994 {
995   // We start from the free shapes (roots in the assembly structure)
996   TDF_LabelSequence aRootLabels;
997   GetFreeShapes(aRootLabels);
998
999   // Iterate over the free shapes
1000   for ( TDF_LabelSequence::Iterator anIt(aRootLabels); anIt.More(); anIt.Next() )
1001   {
1002     TDF_Label aRefLabel = anIt.Value();
1003     if (IsReference(aRefLabel))
1004     {
1005       GetReferredShape(aRefLabel, aRefLabel);
1006     }
1007     const TDF_Label& aRootLab = aRefLabel;
1008     TopoDS_Shape anAssemblyShape;
1009     updateComponent(aRootLab, anAssemblyShape);
1010   }
1011 }
1012
1013 //=======================================================================
1014 //function : IsSubShape
1015 //purpose  : 
1016 //=======================================================================
1017
1018 //static Standard_Boolean CheckSubShape (const TopoDS_Shape &S, const TopoDS_Shape &sub)
1019 //{
1020 //  if ( S.IsSame ( sub ) ) return Standard_True;
1021 //  
1022 //  if ( S.ShapeType() >= sub.ShapeType() ) return Standard_False;
1023 //  
1024 //  for ( TopoDS_Iterator it(S); it.More(); it.Next() ) {
1025 //    if ( CheckSubShape ( it.Value(), sub ) ) return Standard_True;
1026 //  }
1027 //  return Standard_False;
1028 //}
1029
1030 //=======================================================================
1031 //function : IsSubShape
1032 //purpose  : 
1033 //=======================================================================
1034
1035 Standard_Boolean XCAFDoc_ShapeTool::IsSubShape (const TDF_Label &shapeL,
1036                                              const TopoDS_Shape &sub) const
1037 {
1038   Handle(XCAFDoc_ShapeMapTool) A;
1039   if (!shapeL.FindAttribute(XCAFDoc_ShapeMapTool::GetID(), A))
1040   {
1041     A = XCAFDoc_ShapeMapTool::Set(shapeL);
1042     TopoDS_Shape aShape = GetShape(shapeL);
1043     A->SetShape(aShape);
1044   }
1045   
1046   return A->IsSubShape(sub);
1047 }
1048
1049 //=======================================================================
1050 //function : FindSubShape
1051 //purpose  : 
1052 //=======================================================================
1053
1054 Standard_Boolean XCAFDoc_ShapeTool::FindSubShape (const TDF_Label &shapeL,
1055                                                   const TopoDS_Shape &sub,
1056                                                   TDF_Label &L) const
1057 {
1058   // this code is used instead of the following for performance reasons
1059   if ( TNaming_Tool::HasLabel(Label(), sub) ) {
1060     int TransDef = 0;
1061     L = TNaming_Tool::Label(Label(), sub, TransDef);
1062     return ( ! L.IsNull() && L.Father() == shapeL );
1063   }
1064
1065 /*
1066   TDF_ChildIterator chldLabIt(shapeL);
1067   for (; chldLabIt.More(); chldLabIt.Next() ) {
1068     TDF_Label subLabel = chldLabIt.Value();
1069     TopoDS_Shape S;
1070     if ( GetShape ( subLabel, S ) && S.IsSame ( sub ) ) {
1071       L = subLabel;
1072       return Standard_True;
1073     }
1074   }
1075 */
1076   return Standard_False;
1077 }
1078
1079 //=======================================================================
1080 //function : AddSubShape
1081 //purpose  : 
1082 //=======================================================================
1083
1084 TDF_Label XCAFDoc_ShapeTool::AddSubShape (const TDF_Label &shapeL,
1085                                           const TopoDS_Shape &sub) const
1086 {
1087   TDF_Label L;
1088   if ( FindSubShape ( shapeL, sub, L ) ) return L;
1089   
1090   if (!IsSubShape(shapeL, sub))
1091     return TDF_Label();
1092   
1093   TDF_TagSource aTag;
1094   L = aTag.NewChild(shapeL);
1095   
1096   TNaming_Builder tnBuild(L);
1097   tnBuild.Generated(sub);
1098
1099 //  if(!mySubShapes.IsBound(sub))
1100 //    mySubShapes.Bind(sub,L);
1101    
1102   return L;
1103 }
1104
1105
1106 //=======================================================================
1107 //function : FindMainShapeUsingMap
1108 //purpose  : 
1109 //=======================================================================
1110
1111 TDF_Label XCAFDoc_ShapeTool::FindMainShapeUsingMap(const TopoDS_Shape &sub) const
1112 {
1113   //for(Standard_Integer i=1; i<=myNotAssemblies.Length(); i++) {
1114   //  TDF_Label L = myNotAssemblies.Value(i);
1115   //  if(IsSubShape(L,sub)) return L;
1116   //}
1117   if(mySubShapes.IsBound(sub))
1118     return mySubShapes.Find(sub);
1119   TDF_Label L0;
1120   return L0;
1121 }
1122
1123
1124 //=======================================================================
1125 //function : FindMainShape
1126 //purpose  : 
1127 //=======================================================================
1128
1129 TDF_Label XCAFDoc_ShapeTool::FindMainShape (const TopoDS_Shape &sub) const
1130 {
1131   TDF_ChildIterator it(Label());
1132   for (; it.More(); it.Next()) {
1133     TDF_Label L = it.Value();
1134     if ( ! IsAssembly ( L ) && IsSubShape ( L, sub ) ) return L;
1135   }
1136   TDF_Label L0;
1137   return L0;
1138 }
1139
1140
1141 //=======================================================================
1142 //function : GetSubShapes
1143 //purpose  : 
1144 //=======================================================================
1145
1146 Standard_Boolean XCAFDoc_ShapeTool::GetSubShapes (const TDF_Label &L, 
1147                                                TDF_LabelSequence& Labels)
1148 {
1149   TDF_ChildIterator It(L);
1150   for (; It.More(); It.Next() ) {
1151     TDF_Label sub = It.Value();
1152     if ( IsSubShape ( sub ) ) Labels.Append ( sub );
1153   }
1154   return Labels.Length() >0;
1155 }
1156
1157 //=======================================================================
1158 //function : BaseLabel
1159 //purpose  : 
1160 //=======================================================================
1161
1162 TDF_Label XCAFDoc_ShapeTool::BaseLabel () const
1163 {
1164   return Label();
1165 }
1166
1167 //=======================================================================
1168 //function : DumpAssembly
1169 //purpose  : recursive part of Dump()
1170 //=======================================================================
1171
1172 static void DumpAssembly(Standard_OStream& theDumpLog,
1173                          const TDF_Label L,
1174                          const Standard_Integer level,
1175                          const Standard_Boolean deep)
1176 {
1177   TopoDS_Shape S;
1178   XCAFDoc_ShapeTool::GetShape(L, S);
1179   if(S.IsNull())
1180     return;
1181   for (Standard_Integer i=0; i<level; i++)
1182     theDumpLog<<"\t";
1183   
1184   TCollection_AsciiString Entry;
1185   TDF_Tool::Entry(L, Entry);
1186   
1187   if(XCAFDoc_ShapeTool::IsAssembly(L))
1188   {
1189     theDumpLog<<"ASSEMBLY ";
1190   }
1191   else if (XCAFDoc_ShapeTool::IsSimpleShape(L))
1192   {
1193     if(L.Father().Father().Father().IsRoot())
1194       theDumpLog<<"PART ";
1195   }
1196   else
1197   {
1198     theDumpLog<<"INSTANCE ";
1199   }
1200   TopAbs::Print(S.ShapeType(), theDumpLog);
1201
1202   theDumpLog<<" "<<Entry;
1203   if(XCAFDoc_ShapeTool::IsReference(L))
1204   {
1205     Handle(TDataStd_TreeNode) aRef;
1206     L.FindAttribute(XCAFDoc::ShapeRefGUID(), aRef);
1207     TDF_Tool::Entry(aRef->Father()->Label(), Entry);
1208     theDumpLog<<" (refers to "<<Entry<<")";
1209   }
1210   Handle(TDataStd_Name) Name;
1211   if (L.FindAttribute(TDataStd_Name::GetID(), Name))
1212     theDumpLog<<" \""<<Name->Get()<<"\" ";
1213   
1214   if (deep) {
1215     theDumpLog<<"("<<*(void**)&S.TShape();
1216     if (! S.Location().IsIdentity())
1217       theDumpLog<<", "<< *(void**)&S.Location();
1218     theDumpLog<<") ";
1219   }
1220   theDumpLog<<endl;
1221   
1222   Handle(TDataStd_TreeNode) Node;
1223   TDF_ChildIterator NodeIterator(L);
1224   for (; NodeIterator.More(); NodeIterator.Next()) {
1225     DumpAssembly(theDumpLog, NodeIterator.Value(), level+1, deep);
1226   }
1227   if(level == 0)
1228     theDumpLog<<endl;
1229 }
1230
1231 //=======================================================================
1232 //function : Dump
1233 //purpose  : 
1234 //=======================================================================
1235
1236 Standard_OStream& XCAFDoc_ShapeTool::Dump(Standard_OStream& theDumpLog, const Standard_Boolean deep) const
1237 {
1238   Standard_Integer level = 0;
1239 //   TopTools_SequenceOfShape SeqShapes;
1240   TDF_LabelSequence SeqLabels;
1241   GetShapes( SeqLabels);
1242
1243   if (SeqLabels.Length()>0) theDumpLog<<endl;
1244   Standard_Integer i;
1245   for (i=1; i<=SeqLabels.Length(); i++) {
1246     DumpAssembly(theDumpLog, SeqLabels.Value(i), level, deep);
1247   }
1248
1249   SeqLabels.Clear();
1250   GetFreeShapes(SeqLabels);
1251   theDumpLog<<endl<<"Free Shapes: "<<SeqLabels.Length()<<endl;
1252   for (i = 1; i<=SeqLabels.Length(); i++) {
1253     DumpShape(theDumpLog, SeqLabels.Value(i), level, deep);
1254     theDumpLog<<endl;
1255   }
1256   return theDumpLog;
1257 }
1258
1259 //=======================================================================
1260 //function : Dump
1261 //purpose  : override
1262 //=======================================================================
1263
1264 Standard_OStream& XCAFDoc_ShapeTool::Dump(Standard_OStream& theDumpLog) const
1265 {
1266   TDF_Attribute::Dump (theDumpLog);
1267   Dump (theDumpLog, Standard_False);
1268   return theDumpLog;
1269 }
1270
1271 //=======================================================================
1272 //function : DumpShape
1273 //purpose  : 
1274 //=======================================================================
1275
1276 void XCAFDoc_ShapeTool::DumpShape(Standard_OStream& theDumpLog, const TDF_Label& L,const Standard_Integer level,const Standard_Boolean deep)
1277 {
1278   TopoDS_Shape S;
1279   if(! XCAFDoc_ShapeTool::GetShape(L, S) ) return;
1280   for (Standard_Integer i=0; i<level; i++)
1281     theDumpLog<<"\t";
1282   
1283   if(XCAFDoc_ShapeTool::IsAssembly(L))
1284   {
1285     theDumpLog<<"ASSEMBLY ";
1286   }
1287   else if (XCAFDoc_ShapeTool::IsSimpleShape(L))
1288   {
1289     if(L.Father().Father().Father().IsRoot())
1290       theDumpLog<<"PART ";
1291   }
1292   else
1293   {
1294     theDumpLog<<"INSTANCE ";
1295   }  
1296   TopAbs::Print(S.ShapeType(), theDumpLog);
1297   
1298   TCollection_AsciiString Entry;
1299   TDF_Tool::Entry(L, Entry);
1300   theDumpLog<<"  "<<Entry;
1301   if(XCAFDoc_ShapeTool::IsReference(L))
1302   {
1303     Handle(TDataStd_TreeNode) aRef;
1304     L.FindAttribute(XCAFDoc::ShapeRefGUID(), aRef);
1305     TDF_Tool::Entry(aRef->Father()->Label(), Entry);
1306     theDumpLog<<" (refers to "<<Entry<<")";
1307   }
1308   //cout<<endl;
1309   Handle(TDataStd_Name) Name;
1310   if (L.FindAttribute(TDataStd_Name::GetID(),Name)) 
1311     theDumpLog<<" \""<<Name->Get()<<"\" ";
1312   
1313   if (deep) {
1314     theDumpLog<<"("<<*(void**)&S.TShape();
1315     if (! S.Location().IsIdentity())
1316       theDumpLog<<", "<< *(void**)&S.Location();
1317     theDumpLog<<") ";
1318   }
1319 }
1320
1321 //=======================================================================
1322 //function : IsExternRef
1323 //purpose  : 
1324 //=======================================================================
1325
1326 Standard_Boolean XCAFDoc_ShapeTool::IsExternRef(const TDF_Label& L) 
1327 {
1328   Handle(TDataStd_UAttribute) Uattr;
1329   return L.FindAttribute(XCAFDoc::ExternRefGUID(), Uattr);
1330 }
1331
1332 //=======================================================================
1333 //function : SetExternRefs
1334 //purpose  : 
1335 //=======================================================================
1336
1337 void XCAFDoc_ShapeTool::SetExternRefs(const TDF_Label& L,
1338                                       const TColStd_SequenceOfHAsciiString& SHAS) const
1339 {
1340   TDF_Label ShapeLabel = L.NewChild();
1341   TDataStd_UAttribute::Set(ShapeLabel,XCAFDoc::ExternRefGUID());
1342   for(Standard_Integer i=1; i<=SHAS.Length(); i++) {
1343     TDF_Label tmplbl = ShapeLabel.FindChild(i,Standard_True);
1344     Handle(TCollection_HAsciiString) str = SHAS(i);
1345     TCollection_ExtendedString extstr(str->String());
1346     TDataStd_Name::Set(tmplbl,extstr);
1347   }
1348 }
1349
1350 //=======================================================================
1351 //function : SetExternRefs
1352 //purpose  : 
1353 //=======================================================================
1354
1355 TDF_Label XCAFDoc_ShapeTool::SetExternRefs(const TColStd_SequenceOfHAsciiString& SHAS) const
1356 {
1357   TDF_Label ShapeLabel;
1358   TDF_TagSource aTag;
1359   // add a new label
1360   ShapeLabel = aTag.NewChild(Label());
1361   TDataStd_UAttribute::Set(ShapeLabel,XCAFDoc::ExternRefGUID());
1362   for(Standard_Integer i=1; i<=SHAS.Length(); i++) {
1363     TDF_Label tmplbl = ShapeLabel.FindChild(i,Standard_True);
1364     Handle(TCollection_HAsciiString) str = SHAS(i);
1365     TCollection_ExtendedString extstr(str->String());
1366     TDataStd_Name::Set(tmplbl,extstr);
1367   }
1368   return ShapeLabel;
1369 }
1370
1371 //=======================================================================
1372 //function : GetExternRefs
1373 //purpose  : 
1374 //=======================================================================
1375
1376 void XCAFDoc_ShapeTool::GetExternRefs(const TDF_Label& L,
1377                                       TColStd_SequenceOfHAsciiString& SHAS)
1378 {
1379   Handle(TDataStd_Name) TDN;
1380   TDF_Label tmplbl;
1381   for(Standard_Integer i=1; i<=L.NbChildren(); i++) {
1382     tmplbl = L.FindChild(i);
1383     if(tmplbl.FindAttribute(TDataStd_Name::GetID(),TDN)) {
1384       TCollection_ExtendedString extstr = TDN->Get();
1385       Handle(TCollection_HAsciiString) str = 
1386         new TCollection_HAsciiString(TCollection_AsciiString(extstr, '?')); 
1387       SHAS.Append(str);
1388     }
1389   }
1390 }
1391
1392 // API: API work with SHUO (Specified Higher Usage Occurrance) structure
1393
1394 //=======================================================================
1395 //function : GetSHUO
1396 //purpose  : 
1397 //=======================================================================
1398
1399 Standard_Boolean XCAFDoc_ShapeTool::GetSHUO (const TDF_Label& SHUOLabel,
1400                                       Handle(XCAFDoc_GraphNode)& aSHUOAttr)
1401 {
1402   if ( !SHUOLabel.FindAttribute( XCAFDoc::SHUORefGUID(), aSHUOAttr ) )
1403     return Standard_False;
1404   return Standard_True;
1405 }
1406
1407 //=======================================================================
1408 //function : GetAllComponentSHUO
1409 //purpose  : 
1410 //=======================================================================
1411
1412 Standard_Boolean XCAFDoc_ShapeTool::GetAllComponentSHUO (const TDF_Label& theCompLabel,
1413                                                          TDF_AttributeSequence& theSHUOAttrs)
1414 {
1415   TDF_ChildIterator it(theCompLabel); 
1416   for (; it.More(); it.Next()) {
1417     TDF_Label L = it.Value();
1418     Handle(XCAFDoc_GraphNode) aSHUOAttr;
1419     if ( GetSHUO( L, aSHUOAttr ) )
1420       theSHUOAttrs.Append( aSHUOAttr );
1421   }
1422   return (theSHUOAttrs.Length() > 0);
1423 }
1424
1425 //=======================================================================
1426 //function : SetSHUO
1427 //purpose  : 
1428 //=======================================================================
1429
1430 Standard_Boolean XCAFDoc_ShapeTool::SetSHUO (const TDF_LabelSequence& labels,
1431                                              Handle(XCAFDoc_GraphNode)& MainSHUOAttr) const
1432 {
1433   MainSHUOAttr.Nullify();
1434   // check number of labels
1435   if (labels.Length() < 2)
1436     return Standard_False;
1437   // check is all labels contains components of any assemblyies 
1438   Standard_Integer i;
1439   for (i = 1; i <= labels.Length(); i++)
1440     if ( !IsComponent(labels.Value(i)) )
1441       return Standard_False;
1442   
1443   TDF_TagSource aTag;
1444   TDF_Label UpperSubL = aTag.NewChild( labels( 1 ) );
1445   if (theAutoNaming) {
1446     TCollection_ExtendedString Entry("SHUO");
1447     TDataStd_Name::Set(UpperSubL, TCollection_ExtendedString( Entry ));
1448   }
1449   Handle(XCAFDoc_GraphNode) aUpperSHUO;
1450   aUpperSHUO = XCAFDoc_GraphNode::Set( UpperSubL, XCAFDoc::SHUORefGUID() );
1451   // init out argument by main upper usage SHUO
1452   MainSHUOAttr = aUpperSHUO;
1453   // add other next_usage occurrences.
1454   for (i = 2; i <= labels.Length(); i++) {
1455     TDF_Label NextSubL = aTag.NewChild( labels( i ) );
1456     if (theAutoNaming) {
1457       TCollection_ExtendedString EntrySub("SHUO-");
1458       EntrySub += i;
1459       TDataStd_Name::Set(NextSubL, TCollection_ExtendedString( EntrySub ));
1460     }
1461     Handle(XCAFDoc_GraphNode) aNextSHUO;
1462     aNextSHUO = XCAFDoc_GraphNode::Set( NextSubL, XCAFDoc::SHUORefGUID() );
1463     // set references
1464     aUpperSHUO->SetChild( aNextSHUO );
1465     aNextSHUO->SetFather( aUpperSHUO );
1466     // now lets next_usage become upper_usage for next level of SHUO
1467     aUpperSHUO = aNextSHUO;
1468     UpperSubL = NextSubL;
1469   }
1470   
1471   return Standard_True;
1472 }
1473
1474 //=======================================================================
1475 //function : GetSHUOUpperUsage
1476 //purpose  : 
1477 //=======================================================================
1478
1479 Standard_Boolean XCAFDoc_ShapeTool::GetSHUOUpperUsage (const TDF_Label& NextUsageL,
1480                                                        TDF_LabelSequence& aLabels)
1481 {
1482   Handle(XCAFDoc_GraphNode) aNextSHUO;
1483   if( !GetSHUO( NextUsageL, aNextSHUO ) || aNextSHUO->NbFathers()<1 )
1484     return Standard_False;
1485   
1486   // get upper_usage SHAO
1487   for (Standard_Integer i = 1; i <= aNextSHUO->NbFathers(); i++)
1488     aLabels.Append( aNextSHUO->GetFather(i)->Label() );
1489   return Standard_True;
1490 }
1491
1492 //=======================================================================
1493 //function : GetSHUONextUsage
1494 //purpose  : 
1495 //=======================================================================
1496
1497 Standard_Boolean XCAFDoc_ShapeTool::GetSHUONextUsage (const TDF_Label& UpperUsageL,
1498                                                       TDF_LabelSequence& aLabels)
1499 {
1500   Handle(XCAFDoc_GraphNode) aUpperSHUO;
1501   if ( !GetSHUO( UpperUsageL, aUpperSHUO ) || aUpperSHUO->NbChildren()<1 )
1502     return Standard_False;
1503   // get upper_usage SHAO
1504   for (Standard_Integer i = 1; i <= aUpperSHUO->NbChildren(); i++)
1505     aLabels.Append( aUpperSHUO->GetChild(i)->Label() );
1506   return Standard_True;
1507 }
1508
1509 //=======================================================================
1510 //function : RemoveSHUO
1511 //purpose  : 
1512 //=======================================================================
1513
1514 Standard_Boolean XCAFDoc_ShapeTool::RemoveSHUO (const TDF_Label& L) const
1515 {
1516   L.ForgetAllAttributes (Standard_True);
1517   return Standard_True;
1518 }
1519
1520 //=======================================================================
1521 //function : checkForShape
1522 //purpose  : auxilary
1523 //=======================================================================
1524
1525 static Standard_Boolean checkForShape (const TopoDS_Shape& theShape,
1526                                        const TopoDS_Shape& theCurSh,
1527                                        const TDF_Label& theUserL,
1528                                        TDF_LabelSequence& theLabels)
1529 {
1530   // the label of an assembly which contains this component
1531   TDF_Label aSuperUserL = theUserL.Father();
1532   TopLoc_Location aSupLoc, aCompLoc;
1533   aSupLoc = ::XCAFDoc_ShapeTool::GetLocation ( aSuperUserL );
1534   aCompLoc = ::XCAFDoc_ShapeTool::GetLocation ( theUserL );
1535   TopoDS_Shape aCopySh = theCurSh;
1536   aCompLoc = aCompLoc.Multiplied( theCurSh.Location() );
1537   aSupLoc = aSupLoc.Multiplied( aCompLoc );
1538   aCopySh.Location( aSupLoc );
1539   if ( aCopySh.IsSame( theShape ) ) {
1540     theLabels.Prepend( theUserL );
1541     return Standard_True;
1542   }
1543   // try to search deeply (upper by assmebly structure)
1544   TDF_LabelSequence aNewLabels;
1545   for (Standard_Integer j = 1; j <= theLabels.Length(); j++)
1546     aNewLabels.Append( theLabels.Value( j ) );
1547   aNewLabels.Prepend( theUserL );
1548   TDF_LabelSequence aUsers;
1549   ::XCAFDoc_ShapeTool::GetUsers( aSuperUserL, aUsers );
1550   for (Standard_Integer i = 1; i <= aUsers.Length(); i++)
1551     if ( checkForShape( theShape, aCopySh, aUsers.Value( i ), aNewLabels ) ) {
1552       // get solution
1553       theLabels = aNewLabels;
1554       return Standard_True;
1555     }
1556   return Standard_False;
1557 }
1558
1559 //=======================================================================
1560 //function : FindComponent
1561 //purpose  : 
1562 //=======================================================================
1563
1564 Standard_Boolean XCAFDoc_ShapeTool::FindComponent (const TopoDS_Shape& theShape,
1565                                                   TDF_LabelSequence& theLabels) const
1566 {
1567   theLabels.Clear();
1568   // search for a top-level shape that corresponds to this component
1569   TopoDS_Shape S0 = theShape;
1570   TopLoc_Location loc;
1571   S0.Location ( loc );
1572   TDF_Label aRefL = FindShape( S0 );
1573   if (aRefL.IsNull())
1574     return Standard_False; // cannot find top-level shape.
1575   
1576   TDF_LabelSequence aUsers;
1577   ::XCAFDoc_ShapeTool::GetUsers( aRefL, aUsers );
1578   for (Standard_Integer i = 1; i <= aUsers.Length(); i++)
1579     if ( checkForShape( theShape, S0, aUsers.Value( i ), theLabels ) )
1580       break;
1581   
1582   return (theLabels.Length() > 0);
1583 }
1584
1585 //=======================================================================
1586 //function : getShapesOfSHUO
1587 //purpose  : auxilary
1588 //=======================================================================
1589
1590 static Standard_Boolean getShapesOfSHUO (TopLoc_IndexedMapOfLocation& theaPrevLocMap,
1591                                          const Handle(XCAFDoc_ShapeTool)& theSTool,
1592                                          const TDF_Label& theSHUOlab,
1593                                          TopoDS_Shape& theShape)
1594 {
1595   Handle(XCAFDoc_GraphNode) SHUO;
1596   TDF_LabelSequence aLabSeq;
1597   theSTool->GetSHUONextUsage( theSHUOlab, aLabSeq );
1598   if (aLabSeq.Length() >= 1)
1599     for (Standard_Integer i = 1; i <= aLabSeq.Length(); i++) {
1600       TDF_Label aSubCompL = aLabSeq.Value( i );
1601       TopLoc_Location compLoc = XCAFDoc_ShapeTool::GetLocation ( aSubCompL.Father() );
1602       // create new map of laocation (to not merge locations from different shapes)
1603       TopLoc_IndexedMapOfLocation aNewPrevLocMap;
1604       for (Standard_Integer m = 1; m <= theaPrevLocMap.Extent(); m++)
1605         aNewPrevLocMap.Add( theaPrevLocMap.FindKey( m ) );
1606       aNewPrevLocMap.Add( compLoc );
1607       // got for the new sublocations and corresponding shape
1608       getShapesOfSHUO( aNewPrevLocMap, theSTool, aSubCompL, theShape );
1609     }
1610   else {
1611     TopoDS_Shape aSHUO_NUSh = theSTool->GetShape ( theSHUOlab.Father() );
1612     if ( aSHUO_NUSh.IsNull() ) return Standard_False;
1613     // cause got shape with location already.
1614     TopLoc_Location nullLoc;
1615     aSHUO_NUSh.Location ( nullLoc );
1616     // multiply the locations
1617     Standard_Integer intMapLenght = theaPrevLocMap.Extent();
1618     if ( intMapLenght < 1 )
1619       return Standard_False; // should not be, but to avoid exception...?
1620     TopLoc_Location SupcompLoc;
1621     SupcompLoc = theaPrevLocMap.FindKey( intMapLenght );
1622     if (intMapLenght > 1) {
1623       Standard_Integer l = intMapLenght - 1;
1624       while (l >= 1) {
1625         SupcompLoc = theaPrevLocMap.FindKey( l ).Multiplied( SupcompLoc );
1626         l--;
1627       }
1628     }
1629     aSHUO_NUSh.Location( SupcompLoc );
1630     theShape = aSHUO_NUSh;
1631   }
1632   return (!theShape.IsNull());
1633 }
1634
1635 //=======================================================================
1636 //function : GetSHUOInstance
1637 //purpose  : 
1638 //=======================================================================
1639
1640 TopoDS_Shape XCAFDoc_ShapeTool::GetSHUOInstance (const Handle(XCAFDoc_GraphNode)& theSHUO) const
1641 {
1642   TopoDS_Shape aShape;
1643   if (theSHUO.IsNull())
1644     return aShape;
1645   
1646   TDF_Label aSHUOlab = theSHUO->Label();
1647   // get location of the assembly
1648   TopLoc_Location loc = XCAFDoc_ShapeTool::GetLocation ( aSHUOlab.Father().Father() );
1649   // get location of the component
1650   TopLoc_Location compLoc = XCAFDoc_ShapeTool::GetLocation ( aSHUOlab.Father() );
1651   TopLoc_IndexedMapOfLocation aPrevLocMap;
1652   // get previous setted location 
1653   if ( !loc.IsIdentity() )
1654     aPrevLocMap.Add( loc );
1655   aPrevLocMap.Add( compLoc );
1656   // get shape by recurse method
1657   const Handle(XCAFDoc_ShapeTool)& STool = this;
1658   getShapesOfSHUO( aPrevLocMap, STool, aSHUOlab, aShape );
1659   
1660   return aShape;
1661 }
1662
1663 //=======================================================================
1664 //function : getUsersShapesOfSHUO
1665 //purpose  : auxilary
1666 //=======================================================================
1667
1668 static Standard_Boolean getUsersShapesOfSHUO (TopLoc_IndexedMapOfLocation& aPrevLocMap,
1669                                               const Handle(XCAFDoc_ShapeTool)& STool,
1670                                               const TDF_Label& aSHUOlab,
1671                                               const TDF_Label& theUserL,
1672                                               TopTools_SequenceOfShape& theSHUOShapeSeq)
1673 {
1674   TopLoc_IndexedMapOfLocation aNewPrevLocMap;
1675   // get location of the assembly
1676   TopLoc_Location loc = XCAFDoc_ShapeTool::GetLocation ( theUserL.Father() );
1677   // get location of the component
1678   TopLoc_Location compLoc = XCAFDoc_ShapeTool::GetLocation ( theUserL );
1679   // get previous setted location 
1680   aNewPrevLocMap.Add( loc );
1681   aNewPrevLocMap.Add( compLoc );
1682   Standard_Integer i;
1683   for (i = 1; i <= aPrevLocMap.Extent(); i++)
1684     aNewPrevLocMap.Add( aPrevLocMap.FindKey(i) );
1685   TDF_Label L = theUserL.Father();
1686   TDF_LabelSequence usersLab;
1687   ::XCAFDoc_ShapeTool::GetUsers( L, usersLab );
1688   if (usersLab.Length() == 0) {
1689     TopoDS_Shape aShape;
1690     getShapesOfSHUO( aNewPrevLocMap, STool, aSHUOlab, aShape );
1691     if (!aShape.IsNull()) {
1692       theSHUOShapeSeq.Append(aShape);
1693       return Standard_True;
1694     }
1695   }
1696   // now iterates on users of this assembly as component
1697   for ( i = 1; i <= usersLab.Length(); i++ ) {
1698     TDF_Label aNewUserL = usersLab.Value(i);
1699     getUsersShapesOfSHUO( aNewPrevLocMap, STool, aSHUOlab, aNewUserL, theSHUOShapeSeq );
1700   }
1701   
1702   return (theSHUOShapeSeq.Length() > 1);
1703 }
1704
1705 //=======================================================================
1706 //function : GetAllSHUOInstances
1707 //purpose  : auxilary
1708 //=======================================================================
1709
1710 Standard_Boolean XCAFDoc_ShapeTool::GetAllSHUOInstances (const Handle(XCAFDoc_GraphNode)& theSHUO,
1711                                                          TopTools_SequenceOfShape& theSHUOShapeSeq) const
1712 {
1713   if (theSHUO.IsNull())
1714     return Standard_False;
1715
1716   TDF_Label aSHUOlab = theSHUO->Label();
1717   TopLoc_IndexedMapOfLocation aPrevLocMap;
1718   // get location of the assembly
1719   TopLoc_Location loc = XCAFDoc_ShapeTool::GetLocation ( aSHUOlab.Father().Father() );
1720   // get location of the component
1721   TopLoc_Location compLoc = XCAFDoc_ShapeTool::GetLocation ( aSHUOlab.Father() );
1722   // get previous setted location 
1723   if ( !loc.IsIdentity() )
1724     aPrevLocMap.Add( loc );
1725   aPrevLocMap.Add( compLoc );
1726   // get label of assembly
1727   TDF_Label L = aSHUOlab.Father().Father();
1728   TDF_LabelSequence usersLab;
1729   ::XCAFDoc_ShapeTool::GetUsers( L, usersLab );
1730   TopoDS_Shape aShape;
1731   const Handle(XCAFDoc_ShapeTool)& STool = this;
1732   if (usersLab.Length() == 0) {
1733     getShapesOfSHUO( aPrevLocMap, STool, aSHUOlab, aShape );
1734     if (!aShape.IsNull()) {
1735       theSHUOShapeSeq.Append(aShape);
1736       return Standard_True;
1737     }
1738   }
1739   // now iterates on users of this assembly as component
1740   for (Standard_Integer i = 1; i <= usersLab.Length(); i++) {
1741     TDF_Label aUserL = usersLab.Value(i);
1742     getUsersShapesOfSHUO( aPrevLocMap, STool, aSHUOlab, aUserL, theSHUOShapeSeq );
1743   }
1744   
1745   return (theSHUOShapeSeq.Length() > 1);
1746 }
1747
1748 //=======================================================================
1749 //function : SetInstanceSHUO
1750 //purpose  : 
1751 //=======================================================================
1752
1753 Handle(XCAFDoc_GraphNode) XCAFDoc_ShapeTool::SetInstanceSHUO (const TopoDS_Shape& theShape) const
1754 {
1755   Handle(XCAFDoc_GraphNode) SHUO;
1756   TDF_LabelSequence aLabels;
1757   if ( FindComponent( theShape, aLabels ) )
1758     // set shuo structure on labels of component-assembly structure
1759     SetSHUO( aLabels, SHUO );
1760   return SHUO;
1761 }
1762
1763 //=======================================================================
1764 //function : FindSHUO
1765 //purpose  : 
1766 //=======================================================================
1767
1768 Standard_Boolean XCAFDoc_ShapeTool::FindSHUO (const TDF_LabelSequence& theLabels,
1769                                               Handle(XCAFDoc_GraphNode)& theSHUOAttr)
1770 {
1771   TDF_AttributeSequence SHUOAttrs;
1772   TDF_Label aCompLabel = theLabels.Value(1);
1773   if (! ::XCAFDoc_ShapeTool::GetAllComponentSHUO( aCompLabel, SHUOAttrs ) )
1774     return Standard_False;
1775   // WARNING: manage that each SHUO upper_usage have only one SHUO next_usage
1776   for (Standard_Integer i = 1; i <= SHUOAttrs.Length(); i++) {
1777     TDF_LabelSequence aCondidate;
1778     Handle(XCAFDoc_GraphNode) anSHUO = Handle(XCAFDoc_GraphNode)::DownCast(SHUOAttrs.Value(i));
1779     aCondidate.Append( anSHUO->Label().Father() );
1780     while (anSHUO->NbChildren()) {
1781       anSHUO = anSHUO->GetChild( 1 );
1782       aCondidate.Append( anSHUO->Label().Father() );
1783     }
1784     // check the label sequences
1785     Standard_Boolean isEqual = Standard_True;
1786     if (theLabels.Length() != aCondidate.Length())
1787       isEqual = Standard_False;
1788     else
1789       for (Standard_Integer li = 1; li <= theLabels.Length(); li++)
1790         if ( theLabels.Value(li) != aCondidate.Value(li) ) {
1791           isEqual = Standard_False;
1792           break;
1793         }
1794     if (!isEqual)
1795       continue;
1796       
1797     theSHUOAttr = Handle(XCAFDoc_GraphNode)::DownCast(SHUOAttrs.Value(i));
1798     break;
1799   }
1800   return ( !theSHUOAttr.IsNull() );
1801 }
1802
1803 //=======================================================================
1804 //function : Expand
1805 //purpose  : 
1806 //=======================================================================
1807 Standard_Boolean XCAFDoc_ShapeTool::Expand (const TDF_Label& theShapeL)
1808 {
1809   if (theShapeL.IsNull() || IsAssembly(theShapeL))
1810     return Standard_False;
1811
1812   TopoDS_Shape aShape = GetShape(theShapeL);
1813   if (aShape.IsNull())
1814     return Standard_False;
1815
1816   TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1817   Standard_Boolean isExpandedType = aShapeType == TopAbs_COMPOUND || aShapeType == TopAbs_COMPSOLID ||
1818                                     aShapeType == TopAbs_SHELL || aShapeType == TopAbs_WIRE;
1819   if (isExpandedType)
1820   {
1821     //set assembly attribute
1822     TDataStd_UAttribute::Set(theShapeL, XCAFDoc::AssemblyGUID());
1823     TopoDS_Iterator anIter(aShape);
1824     for(; anIter.More(); anIter.Next())
1825     {
1826       TopoDS_Shape aChildShape = anIter.Value();
1827       TDF_Label aChild, aPart;
1828
1829       // Find child shape as subshape of expanded shape
1830       if (!FindSubShape(theShapeL, aChildShape, aChild)) {
1831         // Fast searchig using FindSubShape() can find only the first apparation, try to find manually
1832         TDF_ChildIterator anIt(theShapeL);
1833         for (; anIt.More(); anIt.Next()) {
1834           TDF_Label aSubLabel = anIt.Value();
1835           TopoDS_Shape aSubS;
1836           if (GetShape(aSubLabel, aSubS) && aSubS.IsSame(aChildShape)) {
1837             aChild = aSubLabel;
1838             break;
1839           }
1840         }
1841       }
1842       Handle(TDataStd_Name) anAttr;
1843       //make child (if color isn't set or if it is compound)
1844       if (aChild.IsNull()) {
1845         aChild = AddSubShape(theShapeL, aChildShape);
1846       }
1847       else {
1848         //get name
1849         aChild.FindAttribute(TDataStd_Name::GetID(), anAttr);
1850       }
1851
1852       // Try to find child shape as already existed part
1853       aPart = FindShape(aChildShape.Located(TopLoc_Location()));
1854       if (aPart.IsNull()) {
1855         // Create new part to link child shape
1856         aPart = AddShape(aChildShape.Located(TopLoc_Location()), Standard_False, Standard_False);
1857       }
1858
1859       // Add shape manually, if already existed subshape found instead of creation of new part
1860       if (!aPart.IsNull() && !IsTopLevel(aPart)) {
1861         if (!GetReferredShape(aPart, aPart)) {
1862           TDF_TagSource aTag;
1863           aPart = aTag.NewChild(Label());
1864           SetShape(aPart, aChildShape.Located(TopLoc_Location()));
1865         }
1866       }
1867
1868       // set name to part
1869       if (!anAttr.IsNull()) {
1870         TDataStd_Name::Set(aPart, anAttr->Get());
1871       }
1872       else {
1873         Standard_SStream Stream;
1874         TopAbs::Print(aChildShape.ShapeType(), Stream);
1875         TCollection_AsciiString aName(Stream.str().c_str());
1876         TDataStd_Name::Set(aPart, TCollection_ExtendedString(aName));
1877       }
1878       MakeReference(aChild, aPart, aChildShape.Location());
1879       makeSubShape(aPart, aChildShape, aChildShape.Location());
1880     }
1881     return Standard_True;
1882   }
1883   return Standard_False;
1884 }
1885
1886 //=======================================================================
1887 //function : makeSubShape
1888 //purpose  : 
1889 //=======================================================================
1890
1891 void XCAFDoc_ShapeTool::makeSubShape (const TDF_Label& thePart,
1892                                       const TopoDS_Shape& theShape,
1893                                       const TopLoc_Location& theLoc)
1894 {
1895   TopoDS_Iterator anIter(theShape);
1896   Standard_Boolean isCompoundPart = (GetShape(thePart).ShapeType() == TopAbs_COMPOUND);
1897
1898   for(; anIter.More(); anIter.Next()) {
1899     TopoDS_Shape aChildShape = anIter.Value();
1900     TDF_Label aChildLabel = FindShape(aChildShape,Standard_True);
1901     if(!aChildLabel.IsNull()) { 
1902       //get name
1903       Handle(TDataStd_Name) anAttr;
1904       aChildLabel.FindAttribute(TDataStd_Name::GetID(), anAttr);
1905       TopLoc_Location aSubLoc;
1906       // Calculate location for subshapes of compound parts
1907       if (isCompoundPart) 
1908         aSubLoc = theLoc.Inverted() * aChildShape.Location();
1909       //make subshape
1910       TDF_Label aSubLabel;
1911       if (!FindSubShape(thePart, aChildShape.Located(aSubLoc), aSubLabel)) {
1912         aSubLabel = AddSubShape(thePart, aChildShape.Located(aSubLoc));
1913         //set name to sub shape
1914         if (!anAttr.IsNull()) {
1915           TDataStd_Name::Set(aSubLabel, anAttr->Get());
1916         }
1917         else {
1918           Standard_SStream Stream;
1919           TopAbs::Print(aChildShape.ShapeType(), Stream);
1920           TCollection_AsciiString aName(Stream.str().c_str());
1921           TDataStd_Name::Set(aSubLabel, TCollection_ExtendedString(aName));
1922         }
1923         // Create auxiliary link, it will be removed during moving attributes
1924         MakeReference(aSubLabel, aChildLabel, aChildShape.Location());
1925       }
1926       else {
1927         aChildLabel.ForgetAllAttributes();
1928       }
1929     }
1930     makeSubShape(thePart, aChildShape, theLoc);
1931   }
1932 }
1933
1934 //=======================================================================
1935 //function : updateComponent
1936 //purpose  :
1937 //=======================================================================
1938
1939 Standard_Boolean XCAFDoc_ShapeTool::updateComponent(const TDF_Label& theItemLabel,
1940                                                     TopoDS_Shape&    theUpdatedShape) const
1941 {
1942   if ( !IsAssembly(theItemLabel) )
1943     return Standard_False; // Do nothing for non-assemblies
1944
1945   // Get the currently stored compound for the assembly
1946   TopoDS_Shape aCurrentRootShape;
1947   GetShape(theItemLabel, aCurrentRootShape);
1948
1949   // Get components of the assembly
1950   TDF_LabelSequence aComponentLabs;
1951   GetComponents(theItemLabel, aComponentLabs);
1952
1953   // This flag indicates whether to update the compound of the assembly
1954   Standard_Boolean isModified = Standard_False;
1955
1956   // Compare the number of components in XDE structure with the number of
1957   // components in topological structure. A component may happen to be removed,
1958   // so we have to update the assembly compound
1959   Standard_Integer aNumTopoComponents = 0;
1960   for ( TopoDS_Iterator aTopIt(aCurrentRootShape); aTopIt.More(); aTopIt.Next() )
1961     aNumTopoComponents++;
1962   //
1963   if ( aNumTopoComponents != aComponentLabs.Length() )
1964     isModified = Standard_True;
1965
1966   // Iterate over the assembly components. If at least one component is
1967   // modified (this is the recursive check), then the actually stored
1968   // compound has to be updated
1969   TopTools_ListOfShape aComponentShapes;
1970   //
1971   for ( TDF_LabelSequence::Iterator aCompIt(aComponentLabs); aCompIt.More(); aCompIt.Next() )
1972   {
1973     const TDF_Label& aComponentLab = aCompIt.Value();
1974
1975     // Take the referred assembly item (ultimately, a part for an instance)
1976     TDF_Label aComponentRefLab;
1977     GetReferredShape(aComponentLab, aComponentRefLab);
1978
1979     // Shape comes with some placement transformation here
1980     TopoDS_Shape aComponentShape;
1981     GetShape(aComponentLab, aComponentShape);
1982     TopLoc_Location aComponentLoc = aComponentShape.Location();
1983
1984     // If the component is a sub-assembly, then its associated compound
1985     // has to be processed in the same manner
1986     if ( IsAssembly(aComponentRefLab) )
1987     {
1988       // Recursive call
1989       if ( updateComponent(aComponentRefLab, aComponentShape) )
1990       {
1991         if ( !isModified )
1992           isModified = Standard_True;
1993
1994         aComponentShape.Location(aComponentLoc); // Apply placement
1995       }
1996     }
1997     else
1998     {
1999       // Search for a part in the actual compound of the ultimate assembly.
2000       // If the part is there, then the compound is up-to-date, so it does
2001       // not require rebuilding
2002       Standard_Boolean isPartFound = Standard_False;
2003       for ( TopoDS_Iterator aTopoIt(aCurrentRootShape); aTopoIt.More(); aTopoIt.Next() )
2004       {
2005         if ( aTopoIt.Value() == aComponentShape )
2006         {
2007           isPartFound = Standard_True;
2008           break;
2009         }
2010       }
2011
2012       if ( !isPartFound && !isModified )
2013         isModified = Standard_True; // Part has been modified somewhere, so the compound
2014                                     // has to be rebuilt
2015     }
2016
2017     // Fill the list of shapes composing a new compound for the assembly
2018     aComponentShapes.Append(aComponentShape);
2019   }
2020
2021   // If any component is modified, we update the currently stored shape
2022   if ( isModified )
2023   {
2024     TopoDS_Compound anUpdatedCompound;
2025     BRep_Builder aBB;
2026     aBB.MakeCompound(anUpdatedCompound);
2027
2028     // Compose new compound
2029     for ( TopTools_ListIteratorOfListOfShape aShapeIt(aComponentShapes); aShapeIt.More(); aShapeIt.Next() )
2030     {
2031       aBB.Add( anUpdatedCompound, aShapeIt.Value() );
2032     }
2033
2034     // Store the updated shape as an output
2035     theUpdatedShape = anUpdatedCompound;
2036
2037     // Use topological naming services to store the updated shape in XDE
2038     TNaming_Builder NB(theItemLabel);
2039     NB.Generated(theUpdatedShape);
2040   }
2041
2042   return isModified;
2043 }