0030611: Coding Rules - eliminate GCC compiler warnings -Wcatch-value
[occt.git] / src / TNaming / TNaming_Name.cxx
1 // Created on: 1997-03-21
2 // Created by: Yves FRICAUD
3 // Copyright (c) 1997-1999 Matra Datavision
4 // Copyright (c) 1999-2014 OPEN CASCADE SAS
5 //
6 // This file is part of Open CASCADE Technology software library.
7 //
8 // This library is free software; you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License version 2.1 as published
10 // by the Free Software Foundation, with special exception defined in the file
11 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
12 // distribution for complete text of the license and disclaimer of any warranty.
13 //
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
16
17
18 #include <BRep_Builder.hxx>
19 #include <BRepBuilderAPI_MakeFace.hxx>
20 #include <BRepBuilderAPI_MakeSolid.hxx>
21 #include <BRepBuilderAPI_MakeWire.hxx>
22 #include <BRepTools.hxx>
23 #include <Standard_ConstructionError.hxx>
24 #include <Standard_ErrorHandler.hxx>
25 #include <Standard_NotImplemented.hxx>
26 #include <TColStd_Array1OfInteger.hxx>
27 #include <TDF_Label.hxx>
28 #include <TDF_LabelList.hxx>
29 #include <TDF_LabelMap.hxx>
30 #include <TDF_RelocationTable.hxx>
31 #include <TNaming.hxx>
32 #include <TNaming_Builder.hxx>
33 #include <TNaming_Iterator.hxx>
34 #include <TNaming_ListIteratorOfListOfNamedShape.hxx>
35 #include <TNaming_ListOfNamedShape.hxx>
36 #include <TNaming_Name.hxx>
37 #include <TNaming_NamedShape.hxx>
38 #include <TNaming_Naming.hxx>
39 #include <TNaming_NamingTool.hxx>
40 #include <TNaming_NCollections.hxx>
41 #include <TNaming_NewShapeIterator.hxx>
42 #include <TNaming_ShapesSet.hxx>
43 #include <TNaming_Tool.hxx>
44 #include <TopExp.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopoDS.hxx>
47 #include <TopoDS_Compound.hxx>
48 #include <TopoDS_CompSolid.hxx>
49 #include <TopoDS_Face.hxx>
50 #include <TopoDS_Iterator.hxx>
51 #include <TopoDS_Shape.hxx>
52 #include <TopoDS_Shell.hxx>
53 #include <TopoDS_Solid.hxx>
54 #include <TopoDS_Wire.hxx>
55 #include <TopTools_Array1OfShape.hxx>
56 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
57 #include <TopTools_DataMapOfShapeListOfShape.hxx>
58 #include <TopTools_HArray2OfShape.hxx>
59 #include <TopTools_IndexedMapOfShape.hxx>
60 #include <TopTools_ListIteratorOfListOfShape.hxx>
61 #include <TopTools_ListOfShape.hxx>
62 #include <TopTools_MapIteratorOfMapOfShape.hxx>
63 #include <TopTools_MapOfShape.hxx>
64
65 // mpv modifications 08.04.2002
66 // end of mpv modifications 08.04.2002
67 #ifdef OCCT_DEBUG_DBGTOOLS_WRITE
68 #define MDTV_DEB
69 #define MDTV_DEB_OR
70 #define MDTV_DEB_UNN
71 #define  MDTV_DEB_INT
72 #define MDTV_DEB_GEN
73 #define  MDTV_DEB_MODUN
74 #define MDTV_DEB_FNB
75 #define  MDTV_DEB_WIN
76 #define MDTV_DEB_ARG
77 #define MDTV_DEB_SHELL
78 #endif
79 #ifdef OCCT_DEBUG
80 #include <TCollection_AsciiString.hxx>
81 #include <TDF_Tool.hxx>
82 #include <BRepTools.hxx>
83 #endif
84 #ifdef OCCT_DEBUG
85 #include <TCollection_AsciiString.hxx>
86 #include <TDF_Tool.hxx>
87 #include <TDF_ChildIterator.hxx>
88 #include <TDF_MapIteratorOfLabelMap.hxx>
89 //=======================================================================
90 void PrintEntry(const TDF_Label&       label)
91 {
92   TCollection_AsciiString entry;
93   TDF_Tool::Entry(label, entry);
94   cout << "LabelEntry = "<< entry << endl;
95 }
96 //=======================================================================
97 void PrintEntries(const TDF_LabelMap& map)
98 {
99   cout << "=== Labels Map ===" <<endl;
100   TCollection_AsciiString entry;
101   TDF_MapIteratorOfLabelMap it(map);
102   for(;it.More();it.Next()) {
103     TDF_Tool::Entry(it.Key(), entry);
104       cout << "LabelEntry = "<< entry << endl;
105     }
106 }
107 #ifdef OCCT_DEBUG_DBGTOOLS_WRITE
108 //=======================================================================
109 static void DbgTools_Write(const TopoDS_Shape& shape,
110                       const Standard_CString filename) 
111 {
112   char buf[256];
113   if(strlen(filename) > 256) return;
114   strcpy (buf, filename);
115   char* p = buf;
116   while (*p) {
117     if(*p == ':')
118       *p = '-';
119     p++;
120   }
121   ofstream save (buf);
122   if(!save) 
123     cout << "File " << buf << " was not created: rdstate = " << save.rdstate() << endl;
124   save << "DBRep_DrawableShape" << endl << endl;
125   if(!shape.IsNull()) BRepTools::Write(shape, save);
126   save.close();
127 }
128 //=======================================================================
129 static void DbgTools_Write(const TopTools_IndexedMapOfShape& MS,  const Standard_CString filename) 
130 {
131   if (!MS.IsEmpty ()) {
132     TCollection_AsciiString aNam (filename);
133     for (Standard_Integer anIt = 1; anIt <= MS.Extent(); ++anIt) {
134       TCollection_AsciiString aName = aNam + "_" + (anIt - 1) + ".brep";
135       DbgTools_Write (MS (anIt), aName.ToCString());
136     }
137   }
138 }
139 //=======================================================================
140 static void DbgTools_WriteNSOnLabel (const Handle(TNaming_NamedShape)& NS,  
141                                      const Standard_CString filename) 
142 {
143   if(!NS.IsNull() && !NS->IsEmpty() ) {
144     TCollection_AsciiString aNam (filename);
145     TCollection_AsciiString oldS ("_Old");
146     TCollection_AsciiString newS ("_New_");
147     Standard_Integer i(0);
148     TNaming_Iterator it(NS);
149     for(;it.More(); it.Next(),i++) {
150       TCollection_AsciiString aName1 = aNam + oldS + i + ".brep";
151       TCollection_AsciiString aName2 = aNam + newS + i + ".brep";
152       const TopoDS_Shape& oldShape = it.OldShape();
153       const TopoDS_Shape& newShape = it.NewShape();
154       if(!oldShape.IsNull())
155         DbgTools_Write ( oldShape, aName1.ToCString());
156       if(!newShape.IsNull())
157         DbgTools_Write ( newShape, aName2.ToCString());      
158     }
159   }
160 }
161 #endif
162 #endif
163 //
164 //====================================================================
165 static Standard_Boolean ValidArgs(const TNaming_ListOfNamedShape& Args)
166 {
167   TNaming_ListIteratorOfListOfNamedShape it(Args);
168   for (;it.More();it.Next()) {
169     const Handle(TNaming_NamedShape)& aNS = it.Value();
170     if(aNS.IsNull()) {
171 #ifdef OCCT_DEBUG_ARG 
172       cout << "ValidArgs:: NS (Naming argument) is NULL" <<endl;
173 #endif  
174       return Standard_False;
175     }
176     else 
177       if(aNS->IsEmpty()) {
178 #ifdef OCCT_DEBUG_ARG
179         TCollection_AsciiString entry;
180         TDF_Tool::Entry(aNS->Label(), entry);
181         cout << "ValidArgs:: Empty NS, Label = " << entry <<endl;
182 #endif  
183       return Standard_False;
184     }
185       else  
186         if(!aNS->IsValid()) {
187 #ifdef OCCT_DEBUG_ARG 
188           TCollection_AsciiString entry;
189           TDF_Tool::Entry(aNS->Label(), entry);
190           cout << "ValidArgs::Not valid NS Label = " << entry <<endl;
191 #endif  
192           return Standard_False; 
193         }
194     }
195   return Standard_True;
196 }
197
198 //=======================================================================
199 //function : TNaming_Name
200 //purpose  : 
201 //=======================================================================
202
203 TNaming_Name::TNaming_Name() : 
204    myType(TNaming_UNKNOWN),
205    myIndex(-1)
206 {
207 }
208
209
210 //=======================================================================
211 //function : Type
212 //purpose  : 
213 //=======================================================================
214
215 void TNaming_Name::Type(const TNaming_NameType aType) 
216 {
217   myType = aType;
218 }
219
220 //=======================================================================
221 //function : Type
222 //purpose  : 
223 //=======================================================================
224
225 void TNaming_Name::ShapeType(const TopAbs_ShapeEnum T) 
226 {
227   myShapeType = T;
228 }
229
230 //=======================================================================
231 //function : Shape
232 //purpose  : 
233 //=======================================================================
234
235 void TNaming_Name::Shape(const TopoDS_Shape& theShape) 
236 {
237   myShape = theShape;
238   
239 }
240
241 //=======================================================================
242 //function : Shape
243 //purpose  : 
244 //=======================================================================
245
246 TopoDS_Shape TNaming_Name::Shape() const
247 {
248   return myShape;
249 }
250
251 //=======================================================================
252 //function : Append
253 //purpose  : 
254 //=======================================================================
255
256 void TNaming_Name::Append(const Handle(TNaming_NamedShape)& arg) 
257 {
258   myArgs.Append (arg);
259 }
260
261 //=======================================================================
262 //function : StopNamedShape
263 //purpose  : 
264 //=======================================================================
265
266 void TNaming_Name::StopNamedShape (const Handle(TNaming_NamedShape)& arg) 
267 {
268   myStop = arg;
269 }
270
271 //=======================================================================
272 //function : Index
273 //purpose  : 
274 //=======================================================================
275
276 void TNaming_Name::Index (const Standard_Integer I)
277 {
278   myIndex = I;
279 }
280
281
282 //=======================================================================
283 //function : TNaming_NameType
284 //purpose  : 
285 //=======================================================================
286
287 TNaming_NameType TNaming_Name::Type() const 
288 {
289   return myType;
290 }
291
292 //=======================================================================
293 //function : TNaming_NameType
294 //purpose  : 
295 //=======================================================================
296
297 TopAbs_ShapeEnum TNaming_Name::ShapeType() const 
298 {
299   return myShapeType;
300 }
301
302 //=======================================================================
303 //function : Paste
304 //purpose  : 
305 //=======================================================================
306
307 void TNaming_Name::Paste (TNaming_Name& into,
308                           const Handle(TDF_RelocationTable)& RT) const
309 {
310   into.myType      = myType;
311   into.myShapeType = myShapeType;
312   into.myShape     = myShape;
313   into.myIndex     = myIndex;
314   into.myArgs.Clear();
315 //  into.myOrientation = myOrientation;
316   Handle(TNaming_NamedShape) NS;
317
318   for (TNaming_ListIteratorOfListOfNamedShape it(myArgs); it.More(); it.Next()) {
319     RT->HasRelocation(it.Value(),NS);
320     into.myArgs.Append (NS);
321   }
322   if (!myStop.IsNull()) {
323     RT->HasRelocation(myStop,NS);
324     into.myStop = NS;
325   }
326   if (!myContextLabel.IsNull()) {
327     RT->HasRelocation(myContextLabel,into.myContextLabel);
328   }
329 }
330
331 //=======================================================================
332 //function : Arguments
333 //purpose  : 
334 //=======================================================================
335       
336 const TNaming_ListOfNamedShape& TNaming_Name::Arguments() const
337 {
338   return myArgs;
339 }
340
341 //=======================================================================
342 //function : Arguments
343 //purpose  : 
344 //=======================================================================
345       
346 Handle(TNaming_NamedShape) TNaming_Name::StopNamedShape() const
347 {
348   return myStop;
349 }
350
351 //=======================================================================
352 //function : Index
353 //purpose  : 
354 //=======================================================================
355       
356 Standard_Integer TNaming_Name::Index() const
357 {
358   return myIndex;
359 }
360
361 //=======================================================================
362 //function : MakeShape
363 //purpose  : 
364 //=======================================================================
365
366 static TopoDS_Shape MakeShape (const TopTools_IndexedMapOfShape& MS) 
367 {  
368   if (!MS.IsEmpty ()) {
369     if (MS.Extent() == 1) {
370       return MS (1);
371     }
372     else {
373       TopoDS_Compound C;
374       BRep_Builder B;
375       B.MakeCompound(C);
376       for (Standard_Integer anIt = 1; anIt <= MS.Extent(); ++anIt)
377         B.Add (C, MS (anIt));
378       return C;
379     }
380   }
381   return TopoDS_Shape();  
382 }
383
384 //=======================================================================
385 //function : ShapeWithType
386 //purpose  : Tries to make shape with given type from the given shape
387 //=======================================================================
388
389 static TopoDS_Shape ShapeWithType(const TopoDS_Shape     theShape,
390                                   const TopAbs_ShapeEnum theType ) {
391   if (theShape.IsNull() || theType == TopAbs_SHAPE) return theShape;
392   Standard_Integer aType = theShape.ShapeType();
393   if (aType == theType) return theShape;
394
395   TopTools_ListOfShape aShapes;
396   if (aType == TopAbs_COMPOUND) {
397     TopoDS_Iterator anIter(theShape);
398     if (anIter.More()) aType = anIter.Value().ShapeType();
399     for(;anIter.More();anIter.Next()) aShapes.Append(anIter.Value());
400     if (aType == theType) {
401       if (aShapes.Extent() == 1) return aShapes.First();
402       else return theShape;
403     }
404   } else aShapes.Append(theShape);
405
406   TopoDS_Shape aResult;
407   TopTools_ListIteratorOfListOfShape aListIter(aShapes);
408
409   if (aType < theType) {
410     Standard_Integer aCount;
411     for(aCount=0;aListIter.More();aListIter.Next()) {
412       TopExp_Explorer anExp(aListIter.Value(),theType);
413       if (anExp.More()) {
414         if (!anExp.Current().IsNull()) {
415           aResult = anExp.Current();
416           aCount++;
417           if (aCount > 1) return theShape;
418         }
419       }
420     }
421     if (aCount == 1) return aResult;
422   } else { // if the shape type more complex than shapes from aShapes list, try make it
423     switch (aType) {
424     case TopAbs_VERTEX: // can't do something from vertex
425       break;
426     case TopAbs_EDGE: 
427       {
428         // make wire from edges
429         if (theType <= TopAbs_SOLID) break;
430         BRepBuilderAPI_MakeWire aMakeWire;
431         aMakeWire.Add(aShapes);
432         if (!aMakeWire.IsDone()) return theShape;
433         if (theType == TopAbs_WIRE) return aMakeWire.Wire();
434         aShapes.Clear(); // don't break: we can do something more of it
435         aShapes.Append(aMakeWire.Wire());
436         aListIter.Initialize(aShapes);
437       }
438       Standard_FALLTHROUGH
439     case TopAbs_WIRE: 
440       {
441         // make faceS from wires (one per one)
442         if (theType < TopAbs_SOLID) break;
443         TopTools_ListOfShape aFaces;
444         for(;aListIter.More();aListIter.Next()) {
445           BRepBuilderAPI_MakeFace aMakeFace(TopoDS::Wire(aListIter.Value()));
446           if (!aMakeFace.IsDone()) aFaces.Append(aMakeFace.Face());
447         }
448         if (theType == TopAbs_FACE) {
449           if (aFaces.Extent() == 1) return aFaces.First();
450           return theShape;
451         }
452         aShapes.Assign(aFaces); // don't break: we can do something more of it
453         aListIter.Initialize(aShapes);
454       }
455       Standard_FALLTHROUGH
456     case TopAbs_FACE: 
457       {
458         // make shell from faces
459         if (theType < TopAbs_SOLID) break;
460         BRep_Builder aShellBuilder;
461         TopoDS_Shell aShell;
462         aShellBuilder.MakeShell(aShell);
463         for(;aListIter.More();aListIter.Next()) aShellBuilder.Add(aShell,TopoDS::Face(aListIter.Value()));
464         aShell.Closed (BRep_Tool::IsClosed (aShell));
465         if (theType == TopAbs_SHELL) return aShell;
466         aShapes.Clear(); // don't break: we can do something more of it
467         aShapes.Append(aShell);
468         aListIter.Initialize(aShapes);
469       }
470       Standard_FALLTHROUGH
471     case TopAbs_SHELL: 
472       {
473         // make solids from shells (one per one)
474         TopTools_ListOfShape aSolids;
475         for(;aListIter.More();aListIter.Next()) {
476           BRepBuilderAPI_MakeSolid aMakeSolid(TopoDS::Shell(aListIter.Value()));
477           if (aMakeSolid.IsDone()) aSolids.Append(aMakeSolid.Solid());
478         }
479         if (theType == TopAbs_SOLID) {
480           if (aSolids.Extent() == 1) return aSolids.First();
481           return theShape;
482         }
483         aShapes.Assign(aSolids); // don't break: we can do something more of it
484         aListIter.Initialize(aShapes);
485       }
486       Standard_FALLTHROUGH
487     case TopAbs_SOLID: 
488       {
489         // make compsolid from solids
490         BRep_Builder aCompBuilder;
491         TopoDS_CompSolid aCompSolid;
492         aCompBuilder.MakeCompSolid(aCompSolid);
493         for(;aListIter.More();aListIter.Next()) aCompBuilder.Add(aCompSolid,TopoDS::Solid(aListIter.Value()));
494         if (theType == TopAbs_COMPSOLID) return aCompSolid;
495       }
496     }
497   }
498   return theShape;
499 }
500
501 //=======================================================================
502 //function : FindModifUntil
503 //purpose  : 
504 //=======================================================================
505
506 static Standard_Boolean FindModifUntil (TNaming_NewShapeIterator&         it,
507                                         TopTools_IndexedMapOfShape& MS,
508                                         const TopoDS_Shape&               S,
509                                         const Handle(TNaming_NamedShape)& Context)
510
511 #ifdef OCCT_DEBUG_MODUN
512   if(!Context.IsNull())
513     PrintEntry(Context->Label());
514 #endif
515   Standard_Boolean found = Standard_False;
516   for (; it.More(); it.Next()) {
517     if (!it.Shape().IsNull()) {
518 #ifdef OCCT_DEBUG_MODUN
519       if(!it.NamedShape().IsNull())
520         PrintEntry(it.NamedShape()->Label());
521 #endif
522       if (it.NamedShape() == Context) {
523         MS.Add(S);
524         found = Standard_True;
525       }
526       else { // New shape != Context
527         TNaming_NewShapeIterator it2(it);
528         found = FindModifUntil (it2,MS,it.Shape(),Context);
529       }
530     }
531   }
532   return found;
533 }
534
535 //=======================================================================
536 //function : ModifUntil
537 //purpose  : returns map <theMS> of generators of Target
538 //=======================================================================
539
540 static void SearchModifUntil (const TDF_LabelMap&               /*Valid*/,
541                               const Handle(TNaming_NamedShape)& Target,
542                               const TNaming_ListOfNamedShape& theListOfGenerators,
543                               TopTools_IndexedMapOfShape& theMS)
544 {
545
546 #ifdef OCCT_DEBUG_MODUN
547    DbgTools_WriteNSOnLabel(Target, "SMUntil_"); // Target <== generated
548   Standard_Integer i = 0;
549   TCollection_AsciiString aGen1("Gens_New_"), aGen2("Gented_Old_"), Und("_");
550 #endif 
551   // Test si S apparait comme oldshape dans Context. : Test if S appears as oldshape in Context.
552   Standard_Boolean found = Standard_False;
553   for (TNaming_ListIteratorOfListOfNamedShape it(theListOfGenerators); it.More(); it.Next()) {
554     const Handle(TNaming_NamedShape)& aNS = it.Value();
555 #ifdef OCCT_DEBUG_MODUN  
556     i++;
557     Standard_Integer j = 0;
558 #endif
559     for (TNaming_Iterator itL (aNS); itL.More(); itL.Next()) { // <- generators
560       const TopoDS_Shape& S = itL.NewShape();
561       found = Standard_False;
562       
563 #ifdef OCCT_DEBUG_MODUN
564       j++;
565       Standard_Integer k = 0;
566       TCollection_AsciiString aNam1 = aGen1 + i + Und + j + ".brep";
567       DbgTools_Write(S, aNam1.ToCString());
568       PrintEntry(aNS->Label());//NSLabel
569 #endif   
570       TNaming_Iterator itC (Target);
571       for  (; itC.More(); itC.Next()) {  // <- generated
572         const TopoDS_Shape& OS = itC.OldShape();
573 #ifdef OCCT_DEBUG_MODUN
574         k++;
575         TCollection_AsciiString aNam2 = aGen2 + i + Und + j + Und + k + ".brep";
576         DbgTools_Write(OS, aNam2.ToCString());
577         PrintEntry(Target->Label());//Target Label
578 #endif 
579         if (OS.IsSame(S)) {
580           theMS.Add(S);
581           found = Standard_True;
582 #ifdef OCCT_DEBUG_MODUN
583           cout << aNam2 << " is Same with " << aNam1 <<endl;
584 #endif
585           break;
586         }
587       }
588       if (!found) {
589         TNaming_NewShapeIterator it1(itL);
590         found = FindModifUntil (it1,theMS,S,Target);
591       }
592     }
593   }
594 }
595
596 //=======================================================================
597 //function : ModifUntil
598 //purpose  : 
599 //=======================================================================
600 // NamedShape for this type is assembled from all last modifications of the 
601 // last argument shapes (see method  TNaming_NamingTool::CurrentShape), 
602 // which are not descendants (see method TNaming_NamingTool::BuildDescendants) 
603 // of the stop shape. This type of naming is used for identification shapes, 
604 // which has only one parent with evolution PRIMITIVE (or itself), which 
605 // uniquely identifies it. In most cases stop shape is empty and this algorithm 
606 // is equal to the algorithm for IDENTITY. 
607 //=======================================================================
608 static Standard_Boolean ModifUntil (const TDF_Label&                  L,
609                                     const TDF_LabelMap&               Valid,
610                                     const TNaming_ListOfNamedShape&   Args,
611                                     const Handle(TNaming_NamedShape)& Stop)
612 {
613   TopTools_IndexedMapOfShape MS; 
614   TDF_LabelMap Forbiden;
615   if(!ValidArgs(Args)) return Standard_False;
616   TNaming_NamingTool::BuildDescendants (Stop, Forbiden); // fills Forbidden from Stop
617
618 #ifdef OCCT_DEBUG_GEN  
619   cout <<"Regenerating ModifUntil => ";
620   PrintEntry(L);
621   DbgTools_WriteNSOnLabel(Args.Last(), "ModifUntil-");
622  
623 #endif
624   // all last modifications of the last argument
625   TNaming_NamingTool::CurrentShape  (Valid, Forbiden,Args.Last(),MS); 
626 #ifdef OCCT_DEBUG_GEN  
627   Standard_Integer i(0);
628   TCollection_AsciiString aNam("ModifUnti_MS_");
629   TCollection_AsciiString ext(".brep"); 
630 #endif
631   TNaming_Builder B(L);
632   for (Standard_Integer anItMS = 1; anItMS <= MS.Extent(); ++anItMS) {
633     const TopoDS_Shape& S = MS (anItMS);
634     B.Select(S,S);
635 #ifdef OCCT_DEBUG_GEN  
636     TCollection_AsciiString aName = aNam + ++i + ext;
637     DbgTools_Write(S, aName.ToCString()) ;
638     cout << aName.ToCString() << " TS = " << S.TShape()->This() <<endl;
639 #endif
640   }
641   return Standard_True;
642 }
643
644 //=======================================================================
645 //function : ContShape
646 //purpose  : 
647 //=======================================================================
648 // from the NS of the first argument TNaming_Iterator is started, shape "S" 
649 // is the NewShape from Iterator with index "myIndex" of the Name, this 
650 // shape and all last modifications (except NamedShapes - descendants of 
651 // the stop shape) are the parts of resulting NamedShape.
652 //=======================================================================
653 static Standard_Boolean ConstShape (const TDF_Label&                  L,
654                                     const TDF_LabelMap&               Valid,
655                                     const TNaming_ListOfNamedShape&   Args,
656                                     const Handle(TNaming_NamedShape)& Stop,
657                                     const Standard_Integer            Index)
658 {
659   TopTools_IndexedMapOfShape MS; 
660   TDF_LabelMap Forbiden;
661   if(!ValidArgs(Args)) return Standard_False;
662   TNaming_NamingTool::BuildDescendants (Stop, Forbiden);
663
664   TopoDS_Shape S;
665   Standard_Integer i = 1;
666   for (TNaming_Iterator it(Args.First()); it.More(); it.Next(), i++) {
667     if (Index == i) {
668       S = it.NewShape();
669       break;
670     }
671   }
672   if (S.IsNull()) return Standard_False;
673
674   TNaming_NamingTool::CurrentShapeFromShape  (Valid,Forbiden,L,S,MS);
675
676  
677   TNaming_Builder B(L);
678   for (Standard_Integer anItMS = 1; anItMS <= MS.Extent(); ++anItMS) {
679     const TopoDS_Shape& SS = MS (anItMS);
680     B.Select(SS,SS);
681   }
682   return Standard_True;
683 }
684
685 //=======================================================================
686 //function : Intersection
687 //purpose  : 
688 //=======================================================================
689 //algorithm does next steps:
690 // 1. Sets to the "Forbiden" map  all shapes, which are descendants of stop 
691 //    shape. Named shapes at these labels can't be used.
692 // 2. Takes first argument (with method CurrentShape) and sets map "S" of 
693 //    ancestors (shapes, which belong to this one) of its shape with type 
694 //    "ShapeType" of Name.
695 // 3. Takes next argument of Name (with method CurrentShape) and removes 
696 //    from the map "S" all ancestors, which not belongs to the shape of 
697 //    this argument. This step is repeated for all arguments of this Name.
698 // 4. Adds to the result NamedShape all rest of shapes from the map "S".
699 //=======================================================================
700 static Standard_Boolean Intersection (const TDF_Label&                  L,
701                                       const TDF_LabelMap&               Valid,
702                                       const TNaming_ListOfNamedShape&   Args,
703                                       const Handle(TNaming_NamedShape)& Stop,
704                                       const TopAbs_ShapeEnum            ShapeType,
705                                       const Standard_Integer            Index)
706 {
707   if (Args.IsEmpty()) return Standard_False;
708   if(!ValidArgs(Args)) return Standard_False;
709   TNaming_ListIteratorOfListOfNamedShape it(Args); 
710   TopTools_IndexedMapOfShape MS; 
711   TDF_LabelMap        Forbiden;
712
713 #ifdef OCCT_DEBUG_INT
714   if(!Stop.IsNull() && !Stop->Get().IsNull()) {
715     DbgTools_Write(Stop->Get(), "Ints_Stop.brep");
716     PrintEntry(Stop->Label());
717   }
718   cout <<"Ints: ShapeType = " << ShapeType << endl;
719   cout <<"Argument 1 at ";
720   PrintEntry(it.Value()->Label());
721 #endif 
722
723   TNaming_NamingTool::BuildDescendants (Stop, Forbiden); // <==<1>
724
725 #ifdef OCCT_DEBUG_INT
726   cout << "Intersection:: Valid Map: "<<endl;
727   PrintEntries(Valid);
728   cout << "Intersection:: Forbidden Map: "<<endl;
729   PrintEntries(Forbiden);
730 #endif
731   TopTools_ListOfShape aListOfAnc;
732   TNaming_NamingTool::CurrentShape  (Valid, Forbiden,it.Value(),MS); // first argument
733   TopoDS_Shape  CS = MakeShape(MS);
734   TNaming_ShapesSet S(CS,ShapeType); // <==<2>
735   aListOfAnc.Append(CS);
736 #ifdef OCCT_DEBUG_INT
737   if(!CS.IsNull())
738     DbgTools_Write(CS, "Int_CS_1.brep");
739   Standard_Integer i=2;
740   TCollection_AsciiString aNam("Int_CS_");
741   TCollection_AsciiString ext(".brep");
742  
743 #endif 
744   it.Next();  // <<===<3.1>
745   for (; it.More(); it.Next()) {
746     MS.Clear();
747     TNaming_NamingTool::CurrentShape (Valid,Forbiden,it.Value(),MS);
748     CS = MakeShape(MS);
749     aListOfAnc.Append(CS);
750 #ifdef OCCT_DEBUG_INT
751     TCollection_AsciiString aName = aNam + i++ + ext;      
752     DbgTools_Write(CS, aName.ToCString()) ;
753     cout <<"Argument " << i << " at ";
754     PrintEntry(it.Value()->Label());
755 #endif  
756
757     TNaming_ShapesSet OS(CS,ShapeType);
758     S.Filter(OS); //<<===<3.2>
759 #ifdef OCCT_DEBUG_INT
760     Standard_Integer j = 1;
761     TCollection_AsciiString aNam2("SSMap_"), aName3;
762     TopTools_MapIteratorOfMapOfShape itm(S.Map());
763     for(;itm.More();itm.Next(), j++) {
764       aName3 = aNam2 + i + "_" + j + ".brep";
765       DbgTools_Write(itm.Key(), aName3.ToCString());
766     }
767 #endif 
768   }
769
770 #ifdef OCCT_DEBUG_INT
771   aNam = "Int_S_";
772   i =1;
773 #endif
774
775   TNaming_Builder B(L); //<<===<4>
776   Standard_Boolean isOK(Standard_False);
777   if(S.Map().Extent() > 1 && Index > 0 && ShapeType == TopAbs_EDGE) {
778     Standard_Integer indxE(0), nbE(0), indxW(0),nbW(0), indxF(0);
779     indxE =  Index & 0x000000FF;
780     nbE   = (Index & 0x0000FF00) >> 8;
781     indxW = (Index & 0x000F0000) >> 16;
782     nbW   = (Index & 0x00F00000) >> 20;
783     indxF = (Index & 0x0F000000) >> 24;
784     Standard_Integer k(1);
785     TopoDS_Shape aS;
786     TopTools_ListIteratorOfListOfShape itl(aListOfAnc);
787     for(;itl.More();itl.Next(),k++) {
788       if(indxF == k) {
789         aS = itl.Value();
790         break;
791       }      
792     }
793 #ifdef OCCT_DEBUG_INT
794     cout <<"Kept: indxE = " << indxE  <<" maxENum = " << nbE << " indxW = " <<indxW << " nbW = " <<nbW<<endl;
795 #endif      
796     Standard_Integer aCaseW(0);
797     Standard_Integer aNbW = aS.NbChildren();
798     if(aNbW == nbW) aCaseW = 1;//exact solution for wire (nb of wires is kept)
799     else aCaseW = 2; // indefinite description ==> compound which can include expected wire    
800     if(aCaseW == 1) {      
801       TopoDS_Shape aWire;
802       Standard_Integer i = 1;
803       for (TopoDS_Iterator it2 (aS); it2.More(); it2.Next(), i++)
804       {
805         if(indxW == i) {
806           aWire = it2.Value();
807           break;
808         }
809       }
810       Standard_Integer aCaseE(0);
811       Standard_Integer aNbE = aWire.NbChildren();
812       if(aNbE == nbE) aCaseE = 1;//exact solution for edge
813       else aCaseE = 2;
814       if(aCaseE == 1) {
815         i=1;
816         TopoDS_Shape anEdge;
817         for (TopoDS_Iterator it2 (aWire); it2.More(); it2.Next(), i++) {
818           if(indxE == i) {
819             anEdge = it2.Value();
820             break;
821           }
822         }
823         if(!anEdge.IsNull()) {
824           B.Select(anEdge, anEdge);
825           isOK = Standard_True;
826         }
827       }
828     }   
829   } 
830   if(!isOK)
831 #ifdef OCCT_DEBUG_INT
832     for (TopTools_MapIteratorOfMapOfShape itM(S.Map()); itM.More(); itM.Next(),i++) {
833 #else
834       
835     for (TopTools_MapIteratorOfMapOfShape itM(S.Map()); itM.More(); itM.Next()) {
836 #endif
837       const TopoDS_Shape& S1 = itM.Key();
838 #ifdef OCCT_DEBUG_INT
839       TCollection_AsciiString aName = aNam + i + ext;      
840       DbgTools_Write(S1, aName.ToCString()) ;
841 #endif  
842
843       B.Select(S1,S1);
844       isOK = Standard_True;
845     }
846   return isOK;
847 }
848 //=======================================================================
849 static void KeepInList(const TopoDS_Shape& CS, const TopAbs_ShapeEnum Type, TopTools_ListOfShape& aList)   
850 {
851   if (CS.IsNull()) return;
852
853   if (Type == TopAbs_SHAPE) { 
854     if (CS.ShapeType() == TopAbs_SOLID ||
855         CS.ShapeType() == TopAbs_FACE  ||
856         CS.ShapeType() == TopAbs_EDGE  ||
857         CS.ShapeType() == TopAbs_VERTEX ) {
858       aList.Append(CS);
859     }
860     else {
861       for (TopoDS_Iterator it(CS) ; it.More(); it.Next()) {
862         aList.Append(it.Value());
863       }
864     }
865   }
866   else {
867     if (Type > CS.ShapeType()) {
868       for (TopExp_Explorer exp(CS,Type) ; exp.More(); exp.Next()) {
869         aList.Append(exp.Current());
870       }
871     } else {
872      aList.Append(CS);
873     }
874   }
875 }
876
877 //=======================================================================
878 //function : Union
879 //purpose  : 
880 //=======================================================================
881 // Resulting NamedShape contains compound of next shapes: 
882 // compound of last modifications of each argument (see CurrentShape method) 
883 // without descendants of the stop shape.
884 //=======================================================================
885 static Standard_Boolean Union (const TDF_Label&                  L,
886                                const TDF_LabelMap&               Valid,
887                                const TNaming_ListOfNamedShape&   Args,
888                                const Handle(TNaming_NamedShape)& Stop,
889                                const TopAbs_ShapeEnum            ShapeType,
890                                const TDF_Label&                  ContextLabel)
891 {  
892   if (Args.IsEmpty()) return Standard_False;
893   if(!ValidArgs(Args)) return Standard_False;
894   // temporary solution for Orientation name
895   Standard_Boolean isOr(Standard_True);
896 /* not completed
897   const TDF_Label& aLabel = L.Father();
898   if(!aLabel.IsNull()) {
899   PrintEntry(L);
900   PrintEntry(aLabel);
901     Handle (TNaming_Naming)  Naming;
902     if(aLabel.FindAttribute(TNaming_Naming::GetID(), Naming)) {
903       const TNaming_Name& aName = Naming->GetName();
904       if(aName.Type() == TNaming_ORIENTATION) {
905         const TNaming_ListOfNamedShape&   Args = aName.Arguments();
906         if(Args.Extent() > 2) {
907           const Handle(TNaming_NamedShape)& A = Args.First();
908           if(!A.IsNull()) {
909             PrintEntry(A->Label());
910             if (A->Label() == L) 
911               isOr = Standard_True;         
912           }
913         } else 
914           if(!Args.Extent())
915             isOr = Standard_True;
916       }
917     }
918   }
919 */
920   // end of temp. sol.
921
922   TNaming_ListIteratorOfListOfNamedShape it(Args);
923   TopTools_IndexedMapOfShape MS; 
924   TDF_LabelMap        Forbiden;
925   
926   TNaming_NamingTool::BuildDescendants (Stop, Forbiden);//fill Forbidden
927   TNaming_NamingTool::CurrentShape  (Valid, Forbiden,it.Value(),MS); // fill MS with last modifications of the first argument
928   TopoDS_Shape  CS = MakeShape(MS);
929
930   TopTools_ListOfShape aListS;
931   if(isOr)
932     KeepInList(CS,ShapeType,aListS);
933   TNaming_ShapesSet S(CS,ShapeType);//fill internal map of shapeset by shapes of the specified type
934 #ifdef OCCT_DEBUG_UNN
935   TCollection_AsciiString entry; 
936   TDF_Tool::Entry(it.Value()->Label(), entry);
937   TCollection_AsciiString Nam("Arg_");
938   TCollection_AsciiString aNam = Nam + entry + "_" + "1.brep";
939   DbgTools_Write(CS, aNam.ToCString());
940   Standard_Integer ii = 1;
941 #endif
942   it.Next();
943   for (; it.More(); it.Next()) {
944 #ifdef OCCT_DEBUG_UNN  
945     TDF_Tool::Entry(it.Value()->Label(), entry);
946 #endif
947       MS.Clear();
948       TNaming_NamingTool::CurrentShape (Valid, Forbiden,it.Value(),MS);// fill MS with last modifications of the it.Value()
949       CS = MakeShape(MS);
950       if(isOr)
951         KeepInList(CS,ShapeType,aListS); 
952       TNaming_ShapesSet OS(CS,ShapeType);
953       S.Add(OS); //concatenate both shapesets
954  
955 #ifdef OCCT_DEBUG_UNN 
956     ii++;
957     TCollection_AsciiString aNm = Nam + entry + "_" + ii + ".brep";
958     DbgTools_Write(CS, aNm.ToCString());
959     cout <<"Arg: Entry = " <<entry <<"  TShape = " << CS.TShape() <<endl;
960 #endif
961   }
962
963 // start szy 27.05.08
964   TopoDS_Shape aCand;
965   Standard_Boolean found = Standard_False;
966   if(!ContextLabel.IsNull()) {
967     Handle(TNaming_NamedShape) CNS;
968     ContextLabel.FindAttribute(TNaming_NamedShape::GetID(),CNS);
969     TopoDS_Shape aContext;
970     if(!CNS.IsNull()) {
971       MS.Clear();
972       TNaming_NamingTool::CurrentShape (Valid, Forbiden, CNS, MS);
973       aContext = MakeShape(MS);
974 #ifdef OCCT_DEBUG_UNN 
975       TCollection_AsciiString anEntry;
976       TDF_Tool::Entry(ContextLabel, anEntry);
977       cout << "UNION: Context Label = " <<  anEntry << endl;
978       DbgTools_Write(aContext, "Union_Context.brep");
979       TCollection_AsciiString aN ("aMap_");
980       TopTools_MapIteratorOfMapOfShape it(S.Map());
981       for(Standard_Integer i=1; it.More();it.Next(), i++) {
982         TCollection_AsciiString aName = aN + i + ".brep";
983         DbgTools_Write(it.Key(), aName.ToCString());
984       }
985 #endif
986     }
987     TopTools_ListOfShape aList;
988     TopExp_Explorer anExpl(aContext, ShapeType);
989     for(;anExpl.More(); anExpl.Next()) 
990       aList.Append(anExpl.Current());
991 #ifdef OCCT_DEBUG_UNN
992     cout <<"UNION: ShapeType = " << ShapeType << " List ext = " << aList.Extent()<<endl;
993     TopAbs_ShapeEnum aTyp = TopAbs_SHAPE;
994     TopTools_MapIteratorOfMapOfShape it1 (S.Map());
995     for (int i=1;it1.More();it1.Next(),i++) {
996       cout << "Map("<<i<<"): TShape = " << it1.Key().TShape() << " Orient = " << it1.Key().Orientation() <<endl;
997       aTyp = it1.Key().ShapeType();
998     }
999     
1000     TopExp_Explorer exp(aContext, aTyp);
1001     for(int i =1;exp.More();exp.Next(), i++) {
1002      cout << "Context("<<i<<"): TShape = " << exp.Current().TShape() << " Orient = " << exp.Current().Orientation() <<endl;
1003     }
1004             
1005 #endif
1006     TopTools_ListIteratorOfListOfShape itl(aList);
1007     for(;itl.More();itl.Next()) {
1008       aCand = itl.Value(); 
1009 #ifdef OCCT_DEBUG_UNN 
1010       DbgTools_Write(aCand, "Cand.brep");
1011 #endif
1012       Standard_Integer num = S.Map().Extent();
1013       anExpl.Init(aCand, (ShapeType == TopAbs_WIRE) ? TopAbs_EDGE : TopAbs_FACE); 
1014       for(;anExpl.More();anExpl.Next()) {
1015         if(S.Map().Contains(anExpl.Current()))
1016           num--;
1017       } 
1018       if(num == 0) {
1019         found = Standard_True; 
1020         break;
1021       }
1022     }
1023 // end szy 27.05.08
1024   }
1025
1026   TNaming_Builder B(L);
1027 #ifdef OCCT_DEBUG_UNN
1028   if(!ContextLabel.IsNull()) {
1029     if(found) cout << "UNION: Shape is found in Context" <<endl;
1030     else cout << "UNION: Shape is NOT found in Context" <<endl;
1031   }
1032 #endif
1033   if(found) 
1034     B.Select(aCand, aCand);
1035   else {
1036     BRep_Builder aCompoundBuilder;
1037     TopoDS_Compound aCompound;
1038     aCompoundBuilder.MakeCompound(aCompound);
1039     if(!isOr)
1040       for (TopTools_MapIteratorOfMapOfShape itM(S.Map()); itM.More(); itM.Next()) {
1041         aCompoundBuilder.Add(aCompound,itM.Key());
1042       }
1043     else
1044       for (TopTools_ListIteratorOfListOfShape itL(aListS); itL.More(); itL.Next()) {
1045         aCompoundBuilder.Add(aCompound,itL.Value());
1046       }
1047     TopoDS_Shape aShape = ShapeWithType(aCompound,ShapeType);
1048 #ifdef OCCT_DEBUG_UNN 
1049     DbgTools_Write(aShape, "Union_Selected.brep");
1050     DbgTools_Write(aCompound, "Union_Compound.brep");
1051 #endif
1052     B.Select(aShape,aShape);
1053   }
1054   return Standard_True;
1055 }
1056
1057 //=======================================================================
1058 static TopoDS_Shape FindShape(const TNaming_DataMapOfShapeMapOfShape& DM) 
1059 {
1060   TopoDS_Shape aResult;
1061   Standard_Integer aNum = DM.Extent();
1062   if(aNum < 1) return aResult;  
1063   TopTools_ListOfShape List;
1064   TNaming_DataMapIteratorOfDataMapOfShapeMapOfShape it(DM);
1065   if(it.More()) {
1066     const TopoDS_Shape& aKey1 = it.Key();
1067     const TNaming_MapOfShape& aMap = it.Value();
1068
1069     TNaming_MapIteratorOfMapOfShape itm(aMap); // iterate first map
1070     for (;itm.More();itm.Next()) {
1071       const TopoDS_Shape& aS = itm.Key(); // element of the first map
1072       Standard_Boolean isCand(Standard_True); // aS is a Candidate
1073       TNaming_DataMapIteratorOfDataMapOfShapeMapOfShape it2(DM);
1074       for (;it2.More();it2.Next()) {
1075         const TopoDS_Shape& aKey2 = it2.Key();
1076         if(aKey2 == aKey1) continue;
1077         const TNaming_MapOfShape& aMap2 = it2.Value();
1078         if(!aMap2.Contains(aS)) isCand = Standard_False;
1079       } 
1080       if(isCand)
1081         List.Append(aS);
1082     }
1083   }
1084   if(List.IsEmpty()) return aResult;
1085   if(List.Extent() == 1) return List.First();
1086   TopTools_ListIteratorOfListOfShape itl (List);
1087   TopoDS_Compound Compound;
1088   BRep_Builder B;
1089   B.MakeCompound(Compound);
1090   for (; itl.More(); itl.Next()){ 
1091     B.Add(Compound,itl.Value());
1092   }
1093   return Compound; 
1094 }
1095
1096 //=======================================================================
1097 //function : Generation
1098 //purpose  : Resolves Name from arguments: arg1 - generated (target shape)
1099 //         : arg2 - the generator: the oldest ancestor (usually NS with 
1100 //         : PRIMITIVE evolution. (See TNaming_Localizer::FindGenerator).
1101 //         : Resulting NamedShape contains shape, which is in the first 
1102 //         : argument NamedShape and is modification of the last argument NS.
1103 //=======================================================================
1104
1105 static Standard_Boolean  Generated (const TDF_Label&                L,
1106                                     const TDF_LabelMap&             Valid,
1107                                     const TNaming_ListOfNamedShape& Args)
1108 {
1109   if (Args.Extent() < 2) {
1110     throw Standard_ConstructionError("TNaming_Name::Solve: => Generated");
1111   }
1112   // First argument : label of generation
1113   // Next arguments : generators.
1114
1115   if(!ValidArgs(Args)) return Standard_False;
1116
1117   TDF_Label   LabelOfGeneration = Args.First()->Label();
1118 #ifdef OCCT_DEBUG_GEN
1119       DbgTools_Write(Args.First()->Get(),  "Generated.brep") ;
1120 #endif
1121   // Nouvell valeurs des generateurs dans l attribut de generation
1122   TopTools_IndexedMapOfShape aMS;
1123   TNaming_ListOfNamedShape aGenerators; 
1124   aGenerators.Assign(Args); 
1125   aGenerators.RemoveFirst(); 
1126 #ifdef OCCT_DEBUG_GEN
1127       DbgTools_Write(aGenerators.First()->Get(),  "Generators.brep") ;
1128 #endif
1129   SearchModifUntil (Valid, Args.First(), aGenerators, aMS);
1130   Handle(TNaming_Naming) aNaming;
1131   TopoDS_Shape aSelection;
1132   L.FindAttribute(TNaming_Naming::GetID(),aNaming);
1133   if(!aNaming.IsNull()) 
1134     aSelection = aNaming->GetName().Shape();
1135 #ifdef OCCT_DEBUG_GEN
1136   DbgTools_Write(aSelection,  "G_Selection.brep") ;
1137   cout << "Generated::SearchModifUntil aMS.Extent() = " << aMS.Extent() <<endl;
1138   DbgTools_Write(aMS, "SearchModifUntil_Result");
1139 #endif
1140    Handle(TNaming_NamedShape) anOldNS;
1141    Standard_Integer aVer = -1;// Initial build of name
1142    L.FindAttribute(TNaming_NamedShape::GetID(),anOldNS);
1143    if(!anOldNS.IsNull()) 
1144      aVer = anOldNS->Version();
1145
1146 #ifdef OCCT_DEBUG_GEN
1147   Standard_Integer i = 0, j=1;
1148   TCollection_AsciiString aNam2("Gen_New_");
1149   TCollection_AsciiString aNam1("Gen_Old_");
1150   TCollection_AsciiString ext(".brep");
1151 #endif
1152   TNaming_Builder B(L); // NS
1153   TopTools_ListOfShape aList;
1154   TNaming_DataMapOfShapeMapOfShape aDM; 
1155   for (Standard_Integer anItMS = 1; anItMS <= aMS.Extent(); ++anItMS) {
1156     const TopoDS_Shape& OS = aMS (anItMS);
1157 #ifdef OCCT_DEBUG_GEN
1158     TCollection_AsciiString aName = aNam1 + ++i + ext;      
1159     DbgTools_Write(OS, aName.ToCString()) ;
1160     Standard_Integer j=0;
1161 #endif
1162     TNaming_MapOfShape aMapDM; 
1163     for (TNaming_NewShapeIterator itNew(OS,L); itNew.More(); itNew.Next()) 
1164       if (itNew.Label() == LabelOfGeneration) {
1165         aMapDM.Add(itNew.Shape());
1166         aList.Append(itNew.Shape());//szy 21.10.03
1167 #ifdef OCCT_DEBUG_GEN
1168         TCollection_AsciiString aName = aNam2 + i +  "_" + ++j + ext;      
1169         DbgTools_Write(itNew.Shape(), aName.ToCString()) ;
1170 #endif
1171       }
1172     if(aMapDM.Extent())
1173       aDM.Bind(OS, aMapDM);
1174   }
1175
1176   if(aVer == -1) { //initial 
1177     Standard_Integer i = 1;
1178     TNaming_Name& aName =  aNaming->ChangeName();
1179     TopTools_ListIteratorOfListOfShape it(aList);
1180     if(!aSelection.IsNull()) {
1181       for(;it.More();it.Next(),i++) {
1182         if(it.Value().IsSame(aSelection)) {
1183           B.Select(it.Value(), it.Value());
1184           aName.Index(i); // for debug - index of selection in the list
1185           break;
1186         }
1187       }
1188     } else {// Selection == Null
1189       for(;it.More();it.Next())
1190         B.Select(it.Value(), it.Value()); 
1191     }
1192   }
1193   else { 
1194     // *** Regeneration *** //
1195     if(aList.Extent() == 1) { // trivial case
1196       B.Select(aList.Last(), aList.Last()); 
1197     } 
1198     else {
1199       TNaming_Name& aName =  aNaming->ChangeName();
1200       const TopAbs_ShapeEnum aType = aName.ShapeType();
1201       TopTools_ListOfShape aList2; 
1202       TopTools_ListIteratorOfListOfShape it(aList);
1203       for(;it.More();it.Next()) {
1204         if(it.Value().ShapeType() == aType) //collect only the same type
1205           aList2.Append(it.Value());
1206       }
1207       if(!aList2.Extent()) return Standard_False; // Empty
1208
1209       Standard_Boolean found = Standard_False;
1210       TopoDS_Shape aShape = FindShape(aDM);
1211 #ifdef OCCT_DEBUG_GEN
1212       if(!aShape.IsNull())
1213         DbgTools_Write(aShape,  "G_FindShape.brep") ;
1214 #endif
1215       if(!aShape.IsNull()) found = Standard_True;
1216 #ifdef OCCT_DEBUG_GEN
1217       cout << "Generated ==>aGenerators.Extent() = " <<aGenerators.Extent() <<" aMS.Extent()= " <<aMS.Extent()<<endl;
1218 #endif
1219       if(found) {
1220 #ifdef OCCT_DEBUG_GEN
1221       cout << "Generated ==> Shape is found!" <<endl;
1222 #endif
1223         TopTools_ListOfShape aLM;
1224         Standard_Boolean aHas = Standard_False;
1225         Standard_Boolean a1NB = Standard_False;
1226         if(aGenerators.Extent() != aMS.Extent()) { //missed generators
1227           aHas = Standard_True;//has lost generatos
1228 #ifdef OCCT_DEBUG_GEN
1229       cout << "Generated ==> has lost generatos!" <<endl;
1230 #endif
1231           for (TNaming_ListIteratorOfListOfNamedShape itg(aGenerators); itg.More(); itg.Next()) {
1232             if(!aMS.Contains(itg.Value()->Get())) 
1233               aLM.Append(itg.Value()->Get());
1234           }
1235           if(aLM.Extent() == 1) {//lost 1
1236             TopTools_ListIteratorOfListOfShape itm(aLM);
1237             TopoDS_Shape aSM = itm.Value(); // Missed
1238       for (Standard_Integer anItMS1 = 1; anItMS1 <= aMS.Extent(); ++anItMS1) {
1239               const TopoDS_Shape& aS = aMS (anItMS1);
1240               if(aSM.ShapeType() == aS.ShapeType()) {
1241                 if(aS.ShapeType() == TopAbs_EDGE) {
1242                   TopoDS_Vertex aVCom;
1243                   if(TopExp::CommonVertex(TopoDS::Edge(aS), TopoDS::Edge(aSM), aVCom))
1244                     {a1NB = Standard_True; 
1245                      break;} //lost only 1 neigbour
1246                 } else if(aS.ShapeType() == TopAbs_FACE) {
1247                   TopExp_Explorer expl1(aS, TopAbs_EDGE);
1248                   for(;expl1.More();expl1.Next()) {
1249                     TopExp_Explorer expl2(aSM, TopAbs_EDGE);
1250                     for(;expl2.More();expl2.Next()) {
1251                       if(expl1.Current().IsSame(expl2.Current()))
1252                         {a1NB = Standard_True;
1253                          break;} //lost only 1 neigbour
1254                     }
1255                   }
1256                 }
1257               }
1258             }
1259 //          if(aShape.ShapeType() == TopAbs_VERTEX && a1NBE) {
1260 //      //if atleast 1 Gen was missed and the Gen is Edge
1261 //            TopTools_ListIteratorOfListOfShape it(aList);
1262 //            for(;it.More();it.Next()) {
1263 //              if(it.Value().ShapeType() == TopAbs_EDGE) {
1264 //                const TopoDS_Shape& aV1 = TopExp::FirstVertex(TopoDS::Edge(it.Value()));
1265 //                const TopoDS_Shape& aV2 = TopExp::LastVertex(TopoDS::Edge(it.Value()));
1266 //                if(aShape.IsSame(aV1)) {aShape2 =  aV2;       cout << "##### => V2 " <<endl;break;}
1267 //                else 
1268 //                  if(aShape.IsSame(aV2)) {aShape2 =  aV1;     cout << "##### => V1 " <<endl;break;}
1269 //              }         
1270 //            }
1271 //          }
1272           }
1273         }
1274         if(!aHas) // all arguments were kept
1275           B.Select(aShape, aShape); //only this case is correct on 100%
1276         else {
1277           if (a1NB) //Has, but may be ...
1278             B.Select(aShape, aShape);   
1279           else { 
1280             // put Compound, may be if possible processed later in Sel. Driver
1281             TopTools_ListIteratorOfListOfShape it1(aList2);
1282             for(;it1.More();it1.Next())
1283               B.Select(it1.Value(), it1.Value()); 
1284           }
1285         }
1286     } else 
1287       { //not found
1288 #ifdef OCCT_DEBUG_GEN
1289         cout << "Generated ==> Shape is NOT found! Probably Compound will be built" <<endl;
1290 #endif
1291
1292         TopTools_ListIteratorOfListOfShape it2(aList2);
1293         for(;it2.More();it2.Next())
1294           B.Select(it2.Value(), it2.Value()); 
1295       }
1296     }
1297   }    
1298   return Standard_True;
1299 }
1300
1301 //=======================================================================
1302 //function : Identity
1303 //purpose  : Regenerates Naming attribute with Name = IDENTITY
1304 //=======================================================================
1305 // Name with this type must contain only one NamedShape attribute as argument. 
1306 // Algorithm takes all last modifications of NamedShape of this argument  
1307 // starting with this one ( see method TNaming_NamingTool::CurrentShape ). 
1308 // Algorithm takes only NamedShapes belonging to the labels from the Valid 
1309 // labels map (if it's not empty) and put to the resulting NamedShape as compound. 
1310 //=======================================================================
1311 static Standard_Boolean Identity (const TDF_Label&                L,
1312                                   const TDF_LabelMap&             Valid,
1313                                   const TNaming_ListOfNamedShape& Args,
1314                                   const TopAbs_ShapeEnum          ShapeType)
1315 {
1316   if (Args.Extent() > 2) {
1317     throw Standard_ConstructionError("TNaming_Name::Solve");
1318     }
1319   if(!ValidArgs(Args)) return Standard_False;
1320   const Handle(TNaming_NamedShape)& A = Args.First();
1321   TopTools_IndexedMapOfShape MS;
1322   TDF_LabelMap        Forbiden;
1323   TNaming_NamingTool::CurrentShape (Valid,Forbiden,A,MS);
1324 #ifdef OCCT_DEBUG_SOL2
1325   //TCollection_AsciiString entry;
1326   //TDF_Tool::Entry(L, entry);
1327   //TDF_Tool::Entry(A->Label(), entry);
1328 #endif  
1329   TNaming_Builder B(L);
1330   for (Standard_Integer anItMS = 1; anItMS <= MS.Extent(); ++anItMS) {
1331     const TopoDS_Shape& S = ShapeWithType (MS (anItMS), ShapeType);
1332 #ifdef OCCT_DEBUG_SOL2
1333     //TopAbs_Orientation Or = S.Orientation();
1334 #endif
1335     B.Select(S,S);
1336   }
1337   return Standard_True;
1338 }
1339
1340 //=======================================================================
1341 //function : FilterByNeighbourgs
1342 //purpose  : regenerated the specified shape with help of its neighbours
1343 //=======================================================================
1344 // result -  is a subshape of the first argument of the Name with type = 
1345 // ShapeType of this Name, which has a common subshapes (boundaries) with 
1346 // each neighbour - shapes from the other arguments of the Name.
1347 //=======================================================================
1348 static Standard_Boolean  FilterByNeighbourgs (const TDF_Label&                L,
1349                                               const TDF_LabelMap&             Valid,
1350                                               const TNaming_ListOfNamedShape& Args,
1351                                               const Handle(TNaming_NamedShape)& Stop,
1352                                               const TopAbs_ShapeEnum          ShapeType)
1353 {  
1354
1355   TNaming_Builder B(L); 
1356
1357   TDF_LabelMap        Forbiden;
1358   if(!ValidArgs(Args)) return Standard_False;
1359   TNaming_NamingTool::BuildDescendants (Stop, Forbiden); //all descendants of Stop (New shapes) are forbidden
1360   if (!Stop.IsNull())    Forbiden.Remove(Stop->Label());
1361   //----------------------------------------
1362   // First argument: collection has to be filtered.
1363   //----------------------------------------
1364   Handle(TNaming_NamedShape) Cand  = Args.First(); //collection of candidates
1365    
1366 #ifdef OCCT_DEBUG_FNB
1367   Standard_Integer i = 1;
1368   TCollection_AsciiString aNam("Cand_");
1369   TCollection_AsciiString ext(".brep");
1370   DbgTools_WriteNSOnLabel(Cand, aNam.ToCString());  
1371   cout << "Cand (Args.First()) Label = ";
1372   PrintEntry(Cand->Label());  
1373   cout << "Valid Label map:" <<endl;
1374   PrintEntries(Valid);
1375 #endif
1376
1377   TopTools_IndexedMapOfShape SCand;
1378   TNaming_NamingTool::CurrentShape  (Valid, Forbiden,Cand,SCand);//fills SCand with last modifications of Cand. CandNS should be at the same level (before) as NS of FilterByNBS
1379
1380 #ifdef OCCT_DEBUG_FNB
1381   TCollection_AsciiString aNam2("SCand");
1382   DbgTools_Write(SCand, aNam2.ToCString());  
1383   cout <<"SCand Extent = " << SCand.Extent() << " Expected ShapeType = " << ShapeType << endl;
1384 #endif 
1385
1386   //------------------------------------------------------------
1387   // Autres arguments : contiennent les voisins du bon candidat.
1388   // Other arguments  : contains the neighbors of the good candidate.
1389   //------------------------------------------------------------
1390   TopAbs_ShapeEnum              TC = TopAbs_EDGE;
1391   if (ShapeType == TopAbs_EDGE) TC = TopAbs_VERTEX;
1392   if (ShapeType == TopAbs_VERTEX) TC = TopAbs_VERTEX; // szy 31.03.10 - to process case when Candidate is of type Vertex
1393  
1394 #ifdef OCCT_DEBUG_FNB
1395   i=1;
1396   aNam = "Boundaries";
1397 #endif
1398   Standard_Boolean isDone = Standard_False;
1399   if(SCand.Extent() == 1) { // check if a collection is inside
1400     TopoDS_Shape aS = SCand (1);
1401     if(!aS.IsNull()) 
1402       if(aS.ShapeType() == TopAbs_COMPOUND && aS.ShapeType() != ShapeType) {
1403         SCand.Clear();
1404         TopoDS_Iterator itt(aS);
1405         for(;itt.More();itt.Next()) 
1406           SCand.Add(itt.Value());      
1407       }
1408   }
1409   for (Standard_Integer anItSCand = 1; anItSCand <= SCand.Extent(); ++anItSCand) { //1
1410     const TopoDS_Shape& S = SCand (anItSCand);
1411     TopTools_MapOfShape Boundaries;
1412     if(S.ShapeType() == TopAbs_VERTEX) //# szy 31.03.10
1413       Boundaries.Add (S); //#
1414     else  //#
1415       for (TopExp_Explorer exp(S,TC); exp.More(); exp.Next()) { //put boundaries of each candidate (from SCand) to the Boundaries map
1416         Boundaries.Add (exp.Current());
1417 #ifdef OCCT_DEBUG_FNB
1418         TCollection_AsciiString aName = aNam + i++ + ext;      
1419         DbgTools_Write(exp.Current(),  aName.ToCString()) ;
1420 #endif
1421       }
1422     
1423     TNaming_ListIteratorOfListOfNamedShape it(Args); 
1424     it.Next(); 
1425     Standard_Boolean Keep = 1;
1426 #ifdef OCCT_DEBUG_FNB
1427     cout <<"Args number = " << Args.Extent() <<endl;
1428     i=1;
1429     aNam = "Boundaries";
1430 #endif
1431     for ( ; it.More(); it.Next()) { //2 ==> for each Arg
1432       Standard_Boolean Connected = Standard_False;
1433       // Le candidat doit etre  connexe a au moins un shape de
1434       // chaque NamedShape des voisins.
1435       // The candidate should be connectedand and have at least one shape of NamedShape
1436       // of each neighbor.
1437       const Handle(TNaming_NamedShape)& NSVois = it.Value();  //neighbor 
1438
1439 #ifdef OCCT_DEBUG_FNB
1440       DbgTools_WriteNSOnLabel(NSVois, "Next_Neighbor_") ;
1441 #endif
1442       
1443       TopTools_IndexedMapOfShape SVois;
1444       TNaming_NamingTool::CurrentShape  (Valid, Forbiden,NSVois,SVois); // fills SVois with last modifications of NSVois
1445
1446 #ifdef OCCT_DEBUG_FNB
1447       TCollection_AsciiString aNam2("SVois");
1448       DbgTools_Write(SVois, aNam2.ToCString());
1449 #endif 
1450
1451       for (Standard_Integer anItSVois = 1; anItSVois <= SVois.Extent(); ++anItSVois) { //6
1452         const TopoDS_Shape& Vois = SVois (anItSVois);
1453         for (TopExp_Explorer exp1(Vois,TC); exp1.More(); exp1.Next()) { //7
1454           if (Boundaries.Contains(exp1.Current())) {
1455             Connected = Standard_True; // has common boundaries with candidate shape
1456 #ifdef OCCT_DEBUG_FNB
1457             DbgTools_Write(Vois, "Neighbor_Connected.brep");
1458 #endif
1459             break;
1460           }
1461         } //7
1462         if (Connected) break;
1463       } //6
1464       if (!Connected) {
1465         Keep = 0;
1466         break;
1467       }
1468     } //2
1469     if (Keep) {
1470       B.Select (S,S);
1471           isDone = Standard_True;
1472 #ifdef OCCT_DEBUG_FNB
1473       DbgTools_Write(S,  "FilterByNbs_Sel.brep") ;
1474 #endif
1475     }
1476   } //1
1477   return isDone;
1478 }
1479
1480 //=======================================================================
1481 static const TopoDS_Shape FindSubShapeInAncestor(const TopoDS_Shape& Selection, const TopoDS_Shape& Context )
1482 {
1483 #ifdef OCCT_DEBUG_OR_AG
1484   DbgTools_Write(Selection, "Orientation_Selection.brep");
1485   DbgTools_Write(Context, "Orientation_Context.brep");
1486   TopExp_Explorer expl1(Context, Selection.ShapeType());
1487   int i = 0;
1488   TCollection_AsciiString SS( "Orientation_Current_");
1489   for(;expl1.More(); expl1.Next()) {      
1490     if(expl1.Current().IsSame(Selection)) {
1491       i++;
1492       cout <<"FindSubShape:  = " <<expl1.Current().ShapeType() << " TS = " <<expl1.Current().TShape() << endl;
1493       TCollection_AsciiString nam = SS + i + ".brep";
1494       DbgTools_Write(expl1.Current(), nam.ToCString()); 
1495     }
1496   }
1497 #endif 
1498   if(Selection.ShapeType() != TopAbs_COMPOUND) {
1499     TopExp_Explorer anExpl(Context, Selection.ShapeType());
1500     for(;anExpl.More(); anExpl.Next()) {
1501 #ifdef OCCT_DEBUG_OR_AG
1502       cout <<"FindSubShape:  = " <<anExpl.Current().ShapeType() << " TS = " <<anExpl.Current().TShape()->This() << endl;
1503       DbgTools_Write(anExpl.Current(), "Orientation_Current.brep");
1504 #endif    
1505       if(anExpl.Current().IsSame(Selection)) 
1506         return anExpl.Current();
1507     }
1508   }
1509
1510   return TopoDS_Shape();
1511 }
1512
1513 //=======================================================================
1514 //static Standard_Integer Count(const TopoDS_Shape& S)
1515 //{
1516 //  Standard_Integer N(0);
1517 //  TopoDS_Iterator it(S);
1518 //  for(;it.More();it.Next()) {
1519 //    if(it.Value().ShapeType() != TopAbs_COMPOUND && it.Value().ShapeType() != TopAbs_COMPSOLID)
1520 //      N++;
1521 //    else {
1522 //      N += Count(it.Value());
1523 //    }
1524 //  }
1525 //  return N;
1526 //}
1527 //=======================================================================
1528 static Standard_Integer Aggregation (const TopoDS_Shape& S, const TopoDS_Shape& AS, TNaming_Builder& B)
1529 {
1530   Standard_Integer N(0);
1531   TopoDS_Iterator it(S);
1532   for(;it.More();it.Next()) {
1533     const TopoDS_Shape& sel = it.Value();
1534     if(sel.ShapeType() > TopAbs_COMPSOLID) {
1535       const TopoDS_Shape& CS = FindSubShapeInAncestor(sel, AS);
1536       if(!CS.IsNull()) {
1537         B.Select(CS, CS);
1538         N++;
1539       }
1540     } else 
1541       N += Aggregation(sel, AS, B);    
1542   }
1543   return N;
1544 }
1545
1546 //==========================================================================
1547 //function : Orientation
1548 //purpose  : to solve  ORIENTATION name
1549 // this function explores the second argument | arguments (Context) and 
1550 // keeps at the label (L) the first argument (S) with the orientation it  
1551 // has in the context. Index is used only for Seam edge recomputing 
1552 //==========================================================================
1553 static Standard_Boolean ORientation (const TDF_Label&                L,
1554                                      const TDF_LabelMap&             Valid,
1555                                      const TNaming_ListOfNamedShape& Args,
1556                                      const Handle(TNaming_NamedShape)& Stop,
1557                                      const Standard_Integer          Index)
1558 {
1559
1560   if(!ValidArgs(Args)) return Standard_False;
1561
1562   const Handle(TNaming_NamedShape)& A = Args.First();
1563   TopTools_IndexedMapOfShape MS; 
1564   TDF_LabelMap        Forbiden;
1565   TNaming_NamingTool::BuildDescendants (Stop, Forbiden);
1566   TNaming_NamingTool::CurrentShape (Valid,Forbiden,A,MS);
1567
1568   TopoDS_Shape aShape;
1569   Standard_Boolean isSplit(Standard_False);
1570   if (!MS.IsEmpty ()) {
1571     if (MS.Extent() == 1) {
1572       aShape = MS (1);
1573     } 
1574     else {
1575       isSplit = Standard_True;
1576       aShape = MakeShape(MS);
1577 #ifdef OCCT_DEBUG_OR
1578       for(Standard_Integer anItMS = 1; anItMS <= MS.Extent(); anItMS++) {
1579         TCollection_AsciiString aNam("OR_Selection_");
1580         TCollection_AsciiString aName = aNam + anItMS + ".brep";
1581         DbgTools_Write(MS (anItMS), aName.ToCString());
1582       }
1583 #endif
1584     }
1585   }
1586
1587   TNaming_Builder B(L);
1588   if(aShape.IsNull())
1589     return Standard_False;
1590 #ifdef OCCT_DEBUG_OR
1591   DbgTools_Write(S, "Orientation_S.brep");
1592 #endif
1593
1594   TopTools_ListOfShape aSList;
1595   // tmp. solution
1596   if(aShape.ShapeType() == TopAbs_COMPOUND && !isSplit) {
1597     TopoDS_Iterator it(aShape);
1598     for(;it.More();it.Next())
1599       aSList.Append(it.Value());
1600   } //
1601  
1602   TopTools_IndexedMapOfShape MSC; 
1603   if(aSList.Extent() == 0) {
1604     const Handle(TNaming_NamedShape)& Anc = Args.Last();
1605 #ifdef OCCT_DEBUG_OR
1606     cout << "### ORIENTATION: Ancestor ";
1607     PrintEntry(Anc->Label());
1608 #endif
1609     MSC.Clear();
1610     TNaming_NamingTool::CurrentShape (Valid,Forbiden,Anc,MSC);
1611     if(MSC.Extent() == 1) {
1612       for (Standard_Integer anItMSC = 1; anItMSC <= MSC.Extent(); ++anItMSC) {
1613         const TopoDS_Shape& AS = MSC (anItMSC);
1614 // <=== start 21.10.2009
1615         TopoDS_Shape CS;
1616         if(Index > 0) { //only for seam edge
1617           TopoDS_Iterator itw(AS);
1618           for(;itw.More();itw.Next()) {
1619             Standard_Boolean found(Standard_False);
1620             TopoDS_Iterator it(itw.Value());
1621             for(int i=1;it.More();it.Next(),i++) {
1622               if(i == Index && it.Value().IsSame(aShape)) {
1623                 CS = it.Value();
1624                 found = Standard_True;
1625 #ifdef OCCT_DEBUG_OR
1626                 cout << "ORIENTATION => ORDER = " << i <<endl;
1627 #endif
1628                 break;
1629               }
1630             }
1631             if(found) break;
1632           }
1633         } else
1634           CS =  FindSubShapeInAncestor(aShape, AS);
1635 // <=== end 21.10.2009
1636 #ifdef OCCT_DEBUG_OR
1637         cout << "ORIENTATION: Selection TShape = " <<CS.TShape() <<" Orientation = " << CS.Orientation() <<endl;
1638         cout << "ORIENTATION: Context ShapeType = "<<AS.ShapeType() << " TShape = " <<AS.TShape() <<endl;
1639         DbgTools_Write(AS, "Orientation_Cnt.brep");
1640 #endif
1641         if(!CS.IsNull()) {
1642           B.Select(CS, CS);
1643         } else {
1644           if(!Aggregation(aShape, AS, B))
1645             return Standard_False;        
1646         }
1647       }  
1648     } else {
1649       const TopoDS_Shape  AS = MakeShape(MSC);
1650       const TopoDS_Shape& CS =  FindSubShapeInAncestor(aShape, AS);
1651       if(!CS.IsNull()) {
1652         B.Select(CS, CS);
1653       }  else {
1654         if(!Aggregation(aShape, AS, B)) 
1655           return Standard_False;        
1656       }
1657     }
1658   } else {
1659     TNaming_ListIteratorOfListOfNamedShape it(Args); 
1660     it.Next(); //skip first
1661
1662     // temporary solution. To be optimized (+ has connection with Union name)
1663     Handle(TopTools_HArray2OfShape) Arr; // Arr(1,1) - selection; Arr(1,2) - Context shape
1664     Arr = new TopTools_HArray2OfShape (1, aSList.Extent(), 1, 2);
1665     TopTools_ListIteratorOfListOfShape it1(aSList);
1666     Standard_Integer i = 1;
1667     for(; it1.More(); it1.Next(), it.Next(), i++) {
1668       Arr->SetValue(i, 1, it1.Value());
1669       MSC.Clear();
1670       TNaming_NamingTool::CurrentShape (Valid,Forbiden,it.Value(),MSC);
1671       if(MSC.Extent() == 1) {
1672         Arr->SetValue(i, 2, MSC (1));
1673       } else {
1674         const TopoDS_Shape  AS = MakeShape(MSC);
1675         Arr->SetValue(i, 2, AS);
1676       }
1677     } 
1678     
1679     if(aSList.Extent() == 1) {
1680       const TopoDS_Shape& S = Arr->Value(1,1);
1681       if(S.ShapeType() != TopAbs_COMPOUND) {        
1682         const TopoDS_Shape& CS =  FindSubShapeInAncestor(S, Arr->Value(1,2));
1683         if(!CS.IsNull()) {
1684           B.Select(CS, CS);
1685         } else 
1686           return Standard_False;
1687       } 
1688       else {
1689 #ifdef OCCT_DEBUG_OR
1690         DbgTools_Write(Arr->Value(1,2), "Ancestor.brep");
1691 #endif
1692         if(!Aggregation(S, Arr->Value(1,2), B)) { 
1693           return Standard_False;
1694         }
1695       }
1696     }
1697     else { // > 1   
1698       for(Standard_Integer k = Arr->LowerRow();k <= Arr->UpperRow();k++) {
1699         const TopoDS_Shape& S = Arr->Value(k,1);
1700         const TopoDS_Shape& AC = Arr->Value(k,2);
1701         if(S.ShapeType() != TopAbs_COMPOUND) {      
1702           const TopoDS_Shape& CS =  FindSubShapeInAncestor(S, AC);
1703           if(!CS.IsNull()) {
1704             B.Select(CS, CS);
1705           } else 
1706             return Standard_False;
1707         }
1708         else {
1709 #ifdef OCCT_DEBUG_OR
1710           DbgTools_Write(AC, "Aggregation.brep");
1711 #endif
1712           if(!Aggregation(S, AC, B)) { 
1713             return Standard_False;
1714           }
1715         }
1716       }
1717     }
1718   } // end of tmp. solution 
1719
1720   return Standard_True;
1721 }
1722
1723 //===========================================================================
1724 //function : WireIN
1725 //purpose  : to solve  WIREIN name
1726 //=======================================================================
1727 static Standard_Boolean WireIN(const TDF_Label&                L,
1728                                const TDF_LabelMap&             Valid,
1729                                const TNaming_ListOfNamedShape& Args, 
1730                                    const Handle(TNaming_NamedShape)& Stop,
1731                                    Standard_Integer Index)
1732 {
1733   Standard_Boolean aResult(Standard_False);
1734   if(!ValidArgs(Args)) return aResult;
1735   TopTools_IndexedMapOfShape aMapOfSh;
1736   TDF_LabelMap        aForbiden;
1737   if (Args.Extent() < 1 ) 
1738     throw Standard_ConstructionError("TNaming_Name::Solve");
1739   const Handle(TNaming_NamedShape)& A = Args.First();
1740   TNaming_NamingTool::CurrentShape (Valid,aForbiden,A, aMapOfSh);
1741   if (aMapOfSh.Extent() != 1) return aResult;
1742   const TopoDS_Shape& aCF = aMapOfSh(1);
1743 #ifdef OCCT_DEBUG_WIN
1744   cout <<"MS Extent = " <<MS.Extent() <<endl;
1745   DbgTools_Write(aCF, "Context_Face.brep");
1746 #endif
1747   TNaming_Builder B(L);
1748   if(Index == 1 ){ //Outer wire case 
1749     TopoDS_Wire anOuterWire;
1750     TNaming::OuterWire(TopoDS::Face(aCF), anOuterWire);
1751         if(!anOuterWire.IsNull()) {
1752       B.Select(anOuterWire, anOuterWire);
1753           aResult = Standard_True;
1754         }
1755   } else { //has internal wires
1756         TNaming_ListOfNamedShape ArgsE;
1757     ArgsE.Assign(Args);
1758     ArgsE.RemoveFirst();
1759         // fill Map with edges 
1760     TNaming_ListIteratorOfListOfNamedShape anIter(ArgsE);
1761     TopTools_IndexedMapOfShape MS; 
1762     TDF_LabelMap        Forbiden;
1763   
1764     TNaming_NamingTool::BuildDescendants (Stop, Forbiden);//fill Forbidden
1765     TNaming_NamingTool::CurrentShape  (Valid, Forbiden, anIter.Value(),MS); // fill MS with last modifications of the first additional argument
1766     TopoDS_Shape  CS = MakeShape(MS);
1767
1768     TNaming_ShapesSet aSet(CS,TopAbs_EDGE);//fill internal map of shapeset by shapes of the specified type
1769 #ifdef OCCT_DEBUG_WIN
1770     TCollection_AsciiString entry; 
1771     TDF_Tool::Entry(it.Value()->Label(), entry);
1772     TCollection_AsciiString Nam("Arg_");
1773     TCollection_AsciiString aNam = Nam + entry + "_" + "2.brep";
1774     DbgTools_Write(CS, aNam.ToCString());
1775     Standard_Integer ii = 2;
1776 #endif
1777     anIter.Next();
1778     for (; anIter.More(); anIter.Next()) {
1779 #ifdef OCCT_DEBUG_WIN 
1780       TDF_Tool::Entry(it.Value()->Label(), entry);
1781 #endif
1782       MS.Clear();
1783       TNaming_NamingTool::CurrentShape (Valid, Forbiden,anIter.Value(),MS);// fill MS with last modifications of the it.Value()
1784       CS = MakeShape(MS); 
1785       TNaming_ShapesSet OS(CS,TopAbs_EDGE);
1786       aSet.Add(OS); //concatenate both shapesets
1787  
1788 #ifdef OCCT_DEBUG_WIN
1789       ii++;
1790       TCollection_AsciiString aNm = Nam + entry + "_" + ii + ".brep";
1791       DbgTools_Write(CS, aNm.ToCString());
1792       cout <<"Arg: Entry = " <<entry <<"  TShape = " << CS.TShape() <<endl;
1793 #endif
1794         }
1795
1796 #ifdef OCCT_DEBUG_WIN
1797     cout <<"WIREIN:  Internal Map ext = " << aSet.Map().Extent()<<endl;
1798     TopTools_MapIteratorOfMapOfShape it1 (aSet.Map());
1799     for (int i=1;it1.More();it1.Next(),i++) {
1800       cout << "Map("<<i<<"): TShape = " << it1.Key().TShape() << " Orient = " << it1.Key().Orientation() <<" Type = " <<
1801                   it1.Key().ShapeType()<<endl;
1802     }
1803     
1804     TopExp_Explorer exp(aCF, TopAbs_EDGE);
1805     for(int i =1;exp.More();exp.Next(), i++) {
1806      cout << "Context_Face("<<i<<"): TShape = " << exp.Current().TShape() << " Orient = " << exp.Current().Orientation() <<endl;
1807     }       
1808 #endif
1809 //end for edges
1810         
1811   for (TopoDS_Iterator itF(aCF); itF.More(); itF.Next()) {// find the expected wire in the face
1812     const TopoDS_Shape& S = itF.Value();//wire
1813         if(!S.IsNull()) {
1814 #ifdef OCCT_DEBUG_WIN    
1815       DbgTools_Write(S, "WireIN_S.brep");
1816       cout <<"WIREIN: ShapeType = " << S.ShapeType() << " TS = " << S.TShape()->This() <<endl;
1817 #endif       
1818       if(S.ShapeType() == TopAbs_WIRE) {
1819                 TopTools_MapOfShape aView;
1820                 Standard_Integer aNum(0x7FFFFFFF);
1821             for (TopoDS_Iterator it(S);it.More();it.Next())
1822           aView.Add(it.Value());// edges of wire of the face in map
1823
1824         TopTools_MapIteratorOfMapOfShape it (aSet.Map());
1825                 aNum = aView.Extent();
1826                 if(aNum == aSet.Map().Extent()) {
1827           for (;it.More();it.Next()) {
1828                         if(aView.Contains(it.Key())) {
1829                                 aNum--;
1830                         }
1831                   }
1832                 }
1833                 if(aNum == 0) {
1834                   B.Select(S, S);
1835               aResult = Standard_True;
1836               break;
1837                 }
1838           }
1839         }       
1840   } //
1841
1842   if(!aResult) {
1843         TopoDS_Wire anOuterWire;
1844     TNaming::OuterWire(TopoDS::Face(aCF), anOuterWire);
1845         if(!anOuterWire.IsNull()) {
1846       for (TopoDS_Iterator itF(aCF); itF.More(); itF.Next()) {
1847         const TopoDS_Shape& S = itF.Value();//wire
1848             if(!S.IsNull()&& S.ShapeType() == TopAbs_WIRE) {
1849                   if(S.IsEqual(anOuterWire)) continue;
1850                   B.Select(S, S);
1851                 }
1852           }
1853         }
1854   }
1855   }
1856   return aResult;
1857 }
1858 //===========================================================================
1859 //function : ShellIN
1860 //purpose  : to solve  SHELLIN name
1861 //===========================================================================
1862 static Standard_Boolean ShellIN(const TDF_Label&                L,
1863                                const TDF_LabelMap&             Valid,
1864                                const TNaming_ListOfNamedShape& Args, 
1865                                    const Handle(TNaming_NamedShape)& Stop,
1866                                    Standard_Integer Index)
1867 {
1868   Standard_Boolean aResult(Standard_False);
1869   if(!ValidArgs(Args)) 
1870           return aResult;
1871   TopTools_IndexedMapOfShape aMapOfSh; 
1872   TDF_LabelMap        aForbiden;
1873   if (Args.Extent() < 1 ) 
1874     throw Standard_ConstructionError("TNaming_Name::Solve");
1875   const Handle(TNaming_NamedShape)& A = Args.First();
1876   TNaming_NamingTool::CurrentShape (Valid,aForbiden,A, aMapOfSh);
1877   if (aMapOfSh.Extent() != 1) return aResult;
1878   const TopoDS_Shape& aCSO = aMapOfSh(1);
1879 #ifdef OCCT_DEBUG_SHELL
1880   cout <<"MS Extent = " <<MS.Extent() <<endl;
1881   DbgTools_Write(aCSO, "Context_Solid.brep");
1882 #endif
1883   TNaming_Builder B(L);
1884   if(Index == 1 ){ //Outer Shell case  
1885         TopoDS_Shell anOuterShell;
1886         TNaming::OuterShell(TopoDS::Solid(aCSO), anOuterShell);
1887         if(!anOuterShell.IsNull()) {
1888       B.Select(anOuterShell, anOuterShell);
1889           aResult = Standard_True;
1890 #ifdef OCCT_DEBUG_SHELL      
1891           cout << "Outer Shell case" <<endl;
1892       PrintEntry(L);
1893           DbgTools_Write(anOuterShell, "ShellOut_S.brep");
1894           TopoDS_Iterator it (aCSO);
1895                 for(;it.More();it.Next()){ 
1896           DbgTools_Write(it.Value(), "ShOut_S.brep");
1897                 }
1898 #endif       
1899         }
1900   } else { //has internal Shells
1901         TNaming_ListOfNamedShape ArgsF;
1902     ArgsF.Assign(Args);
1903     ArgsF.RemoveFirst();
1904         // fill Map with faces 
1905     TNaming_ListIteratorOfListOfNamedShape anIter(ArgsF);
1906     TopTools_IndexedMapOfShape MS; 
1907     TDF_LabelMap        Forbiden;
1908   
1909     TNaming_NamingTool::BuildDescendants (Stop, Forbiden);//fill Forbidden
1910     TNaming_NamingTool::CurrentShape  (Valid, Forbiden, anIter.Value(),MS); // fill MS with last modifications of the first additional argument
1911     TopoDS_Shape  CS = MakeShape(MS);
1912
1913     TNaming_ShapesSet aSet(CS,TopAbs_FACE);//fill internal map of shapeset by shapes of the specified type
1914 #ifdef OCCT_DEBUG_SHELL
1915     TCollection_AsciiString entry; 
1916     TDF_Tool::Entry(anIter.Value()->Label(), entry);
1917     TCollection_AsciiString Nam("Arg_");
1918     TCollection_AsciiString aNam = Nam + entry + "_" + "2.brep";
1919     DbgTools_Write(CS, aNam.ToCString());
1920     Standard_Integer ii = 2;
1921 #endif
1922     anIter.Next();
1923     for (; anIter.More(); anIter.Next()) {
1924 #ifdef OCCT_DEBUG_SHELL 
1925       TDF_Tool::Entry(anIter.Value()->Label(), entry);
1926 #endif
1927       MS.Clear();
1928       TNaming_NamingTool::CurrentShape (Valid, Forbiden,anIter.Value(),MS);// fill MS with last modifications of the it.Value()
1929       CS = MakeShape(MS); 
1930       TNaming_ShapesSet OS(CS,TopAbs_FACE);
1931       aSet.Add(OS); //concatenate both shapesets
1932  
1933 #ifdef OCCT_DEBUG_SHELL
1934       ii++;
1935       TCollection_AsciiString aNm = Nam + entry + "_" + ii + ".brep";
1936       DbgTools_Write(CS, aNm.ToCString());
1937       cout <<"Arg: Entry = " <<entry <<"  TShape = " << CS.TShape() <<endl;
1938 #endif
1939         }
1940
1941 #ifdef OCCT_DEBUG_SHELL
1942     cout <<"SHELLIN:  Internal Map ext = " << aSet.Map().Extent()<<endl;
1943     TopTools_MapIteratorOfMapOfShape it1 (aSet.Map());
1944     for (int i=1;it1.More();it1.Next(),i++) {
1945       cout << "Map("<<i<<"): TShape = " << it1.Key().TShape() << " Orient = " << it1.Key().Orientation() <<" Type = " <<
1946                   it1.Key().ShapeType()<<endl;
1947     }
1948     
1949     TopExp_Explorer exp(aCSO, TopAbs_FACE);
1950     for(int i = 1;exp.More();exp.Next(), i++) {
1951      cout << "Context_Solid("<<i<<"): TShape = " << exp.Current().TShape() << " Orient = " << exp.Current().Orientation() <<endl;
1952     }       
1953 #endif
1954 //end for faces
1955         
1956   for (TopoDS_Iterator itS(aCSO); itS.More(); itS.Next()) {// find the expected shell in the solid
1957     const TopoDS_Shape& S = itS.Value();//shell
1958         if(!S.IsNull()) {
1959 #ifdef OCCT_DEBUG_SHELL    
1960       DbgTools_Write(S, "ShellIN_S.brep");
1961       cout <<"SHELLIN: ShapeType = " << S.ShapeType() << " TS = " << S.TShape()->This() <<endl;
1962 #endif       
1963           if(S.ShapeType() == TopAbs_SHELL) {
1964                 TopTools_MapOfShape aView;
1965                 Standard_Integer aNum(0x7FFFFFFF);
1966             for (TopoDS_Iterator it(S);it.More();it.Next())
1967           aView.Add(it.Value());// faces of shell of the solid in map
1968         
1969                 aNum = aView.Extent();
1970                 if(aNum == aSet.Map().Extent()) {
1971                   TopTools_MapIteratorOfMapOfShape it (aSet.Map());
1972           for (;it.More();it.Next()) {
1973                         if(aView.Contains(it.Key())) {
1974                                 aNum--;
1975                         }
1976                   }
1977                 }
1978                 if(aNum == 0) {
1979                   B.Select(S, S);
1980               aResult = Standard_True;
1981               break;
1982                 }
1983           }
1984         }       
1985   } //
1986
1987   if(!aResult) {    
1988         TopoDS_Shell anOuterShell; 
1989         TNaming::OuterShell(TopoDS::Solid(aCSO), anOuterShell);
1990         if(!anOuterShell.IsNull()) {
1991       for (TopoDS_Iterator itS(aCSO); itS.More(); itS.Next()) {
1992         const TopoDS_Shape& S = itS.Value();//shell
1993             if(!S.IsNull()&& S.ShapeType() == TopAbs_SHELL) {
1994                   if(S.IsEqual(anOuterShell)) continue;
1995                   B.Select(S, S);
1996                 }
1997           }
1998         }
1999   }
2000   }
2001   return aResult;
2002 }
2003 #ifdef OCCT_DEBUG
2004 //=======================================================================
2005 static  Standard_CString NameTypeToString (const TNaming_NameType Type)
2006 {
2007   switch(Type)
2008     {
2009     case  TNaming_UNKNOWN             : return "UNKNOWN";
2010     case  TNaming_IDENTITY            : return "IDENTITY";
2011     case  TNaming_MODIFUNTIL          : return "MODIFUNTIL";
2012     case  TNaming_GENERATION          : return "GENERATION";
2013     case  TNaming_INTERSECTION        : return "INTERSECTION";
2014     case  TNaming_UNION               : return "UNION";
2015     case  TNaming_SUBSTRACTION        : return "SUBSTRACTION";
2016     case  TNaming_CONSTSHAPE          : return "CONSTSHAPE";
2017     case  TNaming_FILTERBYNEIGHBOURGS : return "FILTERBYNEIGHBOURGS";
2018     case  TNaming_ORIENTATION         : return "ORIENTATION";
2019     case  TNaming_WIREIN              : return "WIREIN";
2020       default :
2021         throw Standard_DomainError("TNaming_NameType; enum term unknown ");
2022     }
2023 }
2024 #endif
2025 //=======================================================================
2026 //function : Solve
2027 //purpose  : 
2028 //=======================================================================
2029
2030 Standard_Boolean TNaming_Name::Solve(const TDF_Label&    aLab,
2031                                      const TDF_LabelMap& Valid) const
2032 {
2033   Standard_Boolean Done = 0;
2034 #ifdef OCCT_DEBUG_WIN
2035   PrintEntry(aLab);
2036 #endif
2037   try {
2038   OCC_CATCH_SIGNALS
2039   switch (myType) {
2040   case TNaming_UNKNOWN :
2041     {
2042       break;
2043     }  
2044   case TNaming_IDENTITY :
2045     {  
2046       Done = Identity(aLab,Valid,myArgs,myShapeType); 
2047       break;
2048     }
2049   case TNaming_MODIFUNTIL:
2050     {
2051       Done = ModifUntil (aLab,Valid,myArgs,myStop);
2052       break;
2053     }
2054   case TNaming_GENERATION:
2055     {
2056       Done = Generated (aLab,Valid,myArgs);
2057       break;
2058     }
2059   case TNaming_INTERSECTION:
2060     {
2061       Done = Intersection (aLab,Valid,myArgs,myStop,myShapeType,myIndex); 
2062       break;
2063     }
2064   case TNaming_UNION:
2065     {
2066       Done = Union (aLab,Valid,myArgs,myStop,myShapeType, myContextLabel);
2067       break;
2068     }
2069   case TNaming_SUBSTRACTION: 
2070     {
2071       throw Standard_NotImplemented();
2072 //      Done = Substraction (aLab,Valid,myArgs);
2073       break;
2074     }
2075   case TNaming_CONSTSHAPE:
2076     {
2077       Done = ConstShape (aLab,Valid,myArgs,myStop,myIndex);
2078       break;
2079     }
2080   case TNaming_FILTERBYNEIGHBOURGS:
2081     {
2082       Done = FilterByNeighbourgs (aLab,Valid,myArgs,myStop,myShapeType);
2083       break;
2084     }
2085   case TNaming_ORIENTATION: 
2086     {
2087       Done = ORientation (aLab,Valid,myArgs,myStop,myIndex);
2088       break;
2089     }
2090   case TNaming_WIREIN: 
2091     {
2092 #ifdef OCCT_DEBUG_WIN  
2093       cout << "Name::Solve: NameType = " << myType << "  ";
2094   PrintEntry(aLab);
2095 #endif
2096       Done = WireIN (aLab,Valid,myArgs,myStop,myIndex);
2097       break;
2098     }
2099 case TNaming_SHELLIN: 
2100     {
2101 #ifdef OCCT_DEBUG_SHELL
2102       cout << "Name::Solve: NameType = " << myType << "  ";
2103       PrintEntry(aLab);
2104 #endif
2105       Done = ShellIN (aLab,Valid,myArgs,myStop,myIndex);      
2106       break;
2107     }
2108   }
2109 } catch (Standard_Failure const&) {
2110 #ifdef OCCT_DEBUG
2111   cout << "Name::Solve: EXCEPTION==> NameType = " << NameTypeToString(myType) << "  ";
2112   PrintEntry(aLab);
2113 #endif
2114 }
2115   return Done;
2116 }
2117
2118 //=======================================================================
2119 //function : ContextLabel
2120 //purpose  : Set
2121 //=======================================================================
2122
2123 void TNaming_Name::ContextLabel(const TDF_Label& theLabel)
2124 {
2125   myContextLabel = theLabel;
2126 }
2127
2128 //=======================================================================
2129 //function : ContextLabel
2130 //purpose  : Get
2131 //=======================================================================
2132
2133 const TDF_Label&  TNaming_Name::ContextLabel() const
2134
2135   return myContextLabel;
2136 }
2137
2138 //=======================================================================
2139 //function : Orientation
2140 //purpose  : Set
2141 //=======================================================================
2142 void TNaming_Name::Orientation(const TopAbs_Orientation theOrientation) 
2143 {
2144   myOrientation = theOrientation;
2145 }
2146