Salome HOME
Bug 0020229: Perf of MakeSphere and RemoveObject. Allow to re-use empty label, follow...
[modules/geom.git] / src / GEOM / GEOM_Engine.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 #ifdef WNT
23 #pragma warning( disable:4786 )
24 #endif
25
26 #include "GEOM_Engine.hxx"
27
28 #include "GEOM_Solver.hxx"
29 #include "GEOM_Function.hxx"
30 #include "GEOM_ISubShape.hxx"
31 #include "GEOM_SubShapeDriver.hxx"
32 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
33 #include "GEOM_PythonDump.hxx"
34
35 #include "utilities.h"
36
37 #include <TDF_Tool.hxx>
38 #include <TDF_Data.hxx>
39 #include <TDF_Reference.hxx>
40 #include <TDF_LabelSequence.hxx>
41 #include <TDataStd_Integer.hxx>
42 #include <TDataStd_ChildNodeIterator.hxx>
43 #include <TFunction_Driver.hxx>
44 #include <TFunction_DriverTable.hxx>
45
46 #include <TopExp.hxx>
47 #include <TopTools_IndexedMapOfShape.hxx>
48
49 #include <TCollection_AsciiString.hxx>
50 #include <TCollection_ExtendedString.hxx>
51 #include <TColStd_SequenceOfAsciiString.hxx>
52 #include <TColStd_MapOfTransient.hxx>
53 #include <TColStd_HSequenceOfInteger.hxx>
54
55 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
56 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
57
58 #include <set>
59 #include <map>
60 #include <string>
61
62 #include <Standard_Failure.hxx>
63 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
64
65 static GEOM_Engine* TheEngine = NULL;
66
67 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
68 {
69   TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
70   TDF_Tool::Entry(theObject->GetEntry(), anEntry);
71   anID+=(TCollection_AsciiString("_")+anEntry);
72   return anID;
73 }
74
75 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
76 {
77   TCollection_AsciiString anID(theDocID);
78   anID+=(TCollection_AsciiString("_")+theEntry);
79   return anID;
80 }
81
82 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
83 {
84   TCollection_AsciiString aDocID = theID.Token("_");
85   if(aDocID.Length() < 1) return -1;
86   return aDocID.IntegerValue();
87 }
88
89 void ProcessFunction(Handle(GEOM_Function)&   theFunction,
90                      TCollection_AsciiString& theScript,
91                      TDF_LabelMap&            theProcessed,
92                      std::set<std::string>&   theDumpedObjs);
93
94 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
95
96 //=============================================================================
97 /*!
98  *  GetEngine
99  */
100 //=============================================================================
101 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
102
103 //=============================================================================
104 /*!
105  *  SetEngine
106  */
107 //=============================================================================
108 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
109
110 //=============================================================================
111 /*!
112  *  Constructor
113  */
114 //=============================================================================
115 GEOM_Engine::GEOM_Engine()
116 {
117   TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
118
119   _OCAFApp = new GEOM_Application();
120   _UndoLimit = 10;
121 }
122
123 /*!
124  *  Destructor
125  */
126 GEOM_Engine::~GEOM_Engine()
127 {
128   GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
129   for(; It.More(); It.Next())
130     {
131       RemoveObject(Handle(GEOM_Object)::DownCast(It.Value()));
132     }
133
134   //Close all documents not closed
135   for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
136     Close(anItr.Key());
137
138   _mapIDDocument.Clear();
139   _objects.Clear();
140 }
141
142 //=============================================================================
143 /*!
144  *  GetDocument
145  */
146 //=============================================================================
147 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID)
148 {
149   Handle(TDocStd_Document) aDoc;
150   if(!_mapIDDocument.IsBound(theDocID)) {
151     _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
152     aDoc->SetUndoLimit(_UndoLimit);
153     _mapIDDocument.Bind(theDocID, aDoc);
154     TDataStd_Integer::Set(aDoc->Main(), theDocID);
155   }
156
157   return Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
158 }
159
160 //=============================================================================
161 /*!
162  *  GetDocID
163  */
164 //=============================================================================
165 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
166 {
167   if(theDocument.IsNull()) return -1;
168   for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
169     if(anItr.Value() == theDocument) return anItr.Key();
170
171   return -1;
172
173 }
174
175 //=============================================================================
176 /*!
177  *  GetObject
178  */
179 //=============================================================================
180 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry)
181 {
182   TCollection_AsciiString anID = BuildID(theDocID, theEntry);
183   if(_objects.IsBound(anID)) return Handle(GEOM_Object)::DownCast(_objects(anID));
184
185   TDF_Label aLabel;
186   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
187   TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
188   Handle(GEOM_Object) anObject = new GEOM_Object(aLabel);
189
190   _objects.Bind(anID, anObject);
191
192   return anObject;
193 }
194
195 //=============================================================================
196 /*!
197  *  AddObject
198  */
199 //=============================================================================
200 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
201 {
202   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
203   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
204
205   // NPAL18604: use existing label to decrease memory usage,
206   //            if this label has been freed (object deleted)
207   bool useExisting = false;
208   TDF_Label aChild;
209   if (!_lastCleared.IsNull()) {
210     if (_lastCleared.Root() == aDoc->Main().Root()) {
211       useExisting = true;
212       aChild = _lastCleared;
213       // 0020229: if next label exists and is empty, try to reuse it
214       Standard_Integer aNextTag = aChild.Tag() + 1;
215       TDF_Label aNextL = aDoc->Main().FindChild(aNextTag, Standard_False);
216       if (!aNextL.IsNull() && !aNextL.HasAttribute())
217         _lastCleared = aNextL;
218       else
219         _lastCleared.Nullify();
220     }
221   }
222   if (!useExisting) {
223     // create new label
224     aChild = TDF_TagSource::NewChild(aDoc->Main());
225   }
226
227   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
228
229   //Put an object in the map of created objects
230   TCollection_AsciiString anID = BuildIDFromObject(anObject);
231   if(_objects.IsBound(anID)) _objects.UnBind(anID);
232   _objects.Bind(anID, anObject);
233
234   return anObject;
235 }
236
237 //=============================================================================
238 /*!
239  *  AddSubShape
240  */
241 //=============================================================================
242 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
243                                              Handle(TColStd_HArray1OfInteger) theIndices,
244                                              bool isStandaloneOperation)
245 {
246   if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
247
248   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
249   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
250
251   // NPAL18604: use existing label to decrease memory usage,
252   //            if this label has been freed (object deleted)
253   bool useExisting = false;
254   TDF_Label aChild;
255   if (!_lastCleared.IsNull()) {
256     if (_lastCleared.Root() == aDoc->Main().Root()) {
257       useExisting = true;
258       aChild = _lastCleared;
259       // 0020229: if next label exists and is empty, try to reuse it
260       Standard_Integer aNextTag = aChild.Tag() + 1;
261       TDF_Label aNextL = aDoc->Main().FindChild(aNextTag, Standard_False);
262       if (!aNextL.IsNull() && !aNextL.HasAttribute())
263         _lastCleared = aNextL;
264       else
265         _lastCleared.Nullify();
266     }
267   }
268   if (!useExisting) {
269     // create new label
270     aChild = TDF_TagSource::NewChild(aDoc->Main());
271   }
272
273   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
274   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
275   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
276
277   GEOM_ISubShape aSSI(aFunction);
278   aSSI.SetMainShape(aMainShape);
279   aSSI.SetIndices(theIndices);
280
281   try {
282 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
283     OCC_CATCH_SIGNALS;
284 #endif
285     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
286     if (!aSolver.ComputeFunction(aFunction)) {
287       MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
288       return NULL;
289     }
290   }
291   catch (Standard_Failure) {
292     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
293     MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
294     return NULL;
295   }
296
297   //Put an object in the map of created objects
298   TCollection_AsciiString anID = BuildIDFromObject(anObject);
299   if(_objects.IsBound(anID)) _objects.UnBind(anID);
300   _objects.Bind(anID, anObject);
301
302   GEOM::TPythonDump pd (aFunction);
303
304   if (isStandaloneOperation) {
305     pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
306     Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
307     for (; i <= up - 1; i++) {
308       pd << theIndices->Value(i) << ", ";
309     }
310     pd << theIndices->Value(up) << "])";
311   }
312   else
313     pd << "None";
314
315   return anObject;
316 }
317
318 //=============================================================================
319 /*!
320  *  RemoveObject
321  */
322 //=============================================================================
323 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
324 {
325   if (!theObject) return false;
326
327   //Remove an object from the map of available objects
328   TCollection_AsciiString anID = BuildIDFromObject(theObject);
329   if (_objects.IsBound(anID)) _objects.UnBind(anID);
330
331   int nb = theObject->GetNbFunctions();
332   Handle(TDataStd_TreeNode) aNode;
333   for (int i = 1; i<=nb; i++) {
334     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
335     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
336       aNode->Remove();
337   }
338
339   TDF_Label aLabel = theObject->GetEntry();
340   aLabel.ForgetAllAttributes(Standard_True);
341   _lastCleared = aLabel;
342
343   theObject.Nullify();
344
345   return true;
346 }
347
348 //=============================================================================
349 /*!
350  *  Undo
351  */
352 //=============================================================================
353 void GEOM_Engine::Undo(int theDocID)
354 {
355   GetDocument(theDocID)->Undo();
356 }
357
358 //=============================================================================
359 /*!
360  *  Redo
361  */
362 //=============================================================================
363 void GEOM_Engine::Redo(int theDocID)
364 {
365   GetDocument(theDocID)->Redo();
366 }
367
368 //=============================================================================
369 /*!
370  *  Save
371  */
372 //=============================================================================
373 bool GEOM_Engine::Save(int theDocID, char* theFileName)
374 {
375   if(!_mapIDDocument.IsBound(theDocID)) return false;
376   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
377
378   _OCAFApp->SaveAs(aDoc, theFileName);
379
380   return true;
381 }
382
383 //=============================================================================
384 /*!
385  *  Load
386  */
387 //=============================================================================
388 bool GEOM_Engine::Load(int theDocID, char* theFileName)
389 {
390   Handle(TDocStd_Document) aDoc;
391   if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
392     return false;
393   }
394
395   aDoc->SetUndoLimit(_UndoLimit);
396
397   if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
398   _mapIDDocument.Bind(theDocID, aDoc);
399
400   TDataStd_Integer::Set(aDoc->Main(), theDocID);
401
402   return true;
403 }
404
405 //=============================================================================
406 /*!
407  *  Close
408  */
409 //=============================================================================
410 void GEOM_Engine::Close(int theDocID)
411 {
412   if (_mapIDDocument.IsBound(theDocID)) {
413     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
414
415     //Remove all GEOM Objects associated to the given document
416     TColStd_SequenceOfAsciiString aSeq;
417     GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
418     for (; It.More(); It.Next()) {
419       TCollection_AsciiString anObjID (It.Key());
420       Standard_Integer anID = ExtractDocID(anObjID);
421       if (theDocID == anID) aSeq.Append(It.Key());
422     }
423     for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
424
425     _lastCleared.Nullify();
426
427     _mapIDDocument.UnBind(theDocID);
428     _OCAFApp->Close(aDoc);
429     aDoc.Nullify();
430   }
431 }
432
433 //=============================================================================
434 /*!
435  *  DumpPython
436  */
437 //=============================================================================
438 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
439                                                 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
440                                                 bool isPublished,
441                                                 bool& aValidScript)
442 {
443   TCollection_AsciiString aScript;
444   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
445
446   if (aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
447
448   aScript  = "import geompy\n";
449   aScript += "import math\n";
450   aScript += "import SALOMEDS\n\n";
451   aScript += "def RebuildData(theStudy):";
452   aScript += "\n\tgeompy.init_geom(theStudy)";
453
454   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
455
456   Handle(TDataStd_TreeNode) aNode, aRoot;
457   Handle(GEOM_Function) aFunction;
458   TDF_LabelMap aCheckedFuncMap;
459   std::set<std::string> anIgnoreObjMap;
460
461   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
462     TDataStd_ChildNodeIterator Itr(aRoot);
463     for (; Itr.More(); Itr.Next()) {
464       aNode = Itr.Value();
465       aFunction = GEOM_Function::GetFunction(aNode->Label());
466       if (aFunction.IsNull()) {
467         MESSAGE ( "Null function !!!!" );
468         continue;
469       }
470       ProcessFunction(aFunction, aScript, aCheckedFuncMap, anIgnoreObjMap);
471     }
472   }
473
474   Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
475   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
476   // build maps entry <-> studyEntry
477   for (anEntryToNameIt.Initialize( theObjectNames );
478        anEntryToNameIt.More();
479        anEntryToNameIt.Next())
480   {
481     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
482     // look for an object by entry
483     TDF_Label L;
484     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
485     if ( L.IsNull() ) continue;
486     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
487     // fill maps
488     if ( !obj.IsNull() ) {
489       TCollection_AsciiString aStudyEntry (obj->GetAuxData());
490       aEntry2StEntry.Bind( aEntry,  aStudyEntry);
491       aStEntry2Entry.Bind( aStudyEntry, aEntry );
492     }
493   }
494
495   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
496   Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
497   Resource_DataMapOfAsciiStringAsciiString aNameToEntry, anEntryToBadName;
498
499   //Replace entries by the names
500   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
501     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
502   if (aLen == 0) anUpdatedScript = aScript;
503
504   for (Standard_Integer i = 1; i <= aLen; i+=2) {
505     anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
506     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
507     if (theObjectNames.IsBound(anEntry)) {
508       aName = theObjectNames.Find(anEntry);
509       // check validity of aName
510       bool isValidName = true;
511       if ( aName.IsIntegerValue() ) { // aName must not start with a digit
512         aName.Insert( 1, 'a' );
513         isValidName = false;
514       }
515       int p, p2=1; // replace not allowed chars
516       while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
517         aName.SetValue(p, '_');
518         p2=p;
519         isValidName = false;
520       }
521       if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
522       {  // diff objects have same name - make a new name by appending a digit
523         TCollection_AsciiString aName2;
524         Standard_Integer i = 0;
525         do {
526           aName2 = aName + "_" + ++i;
527         } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
528         aName = aName2;
529         isValidName = false;
530       }
531       if ( !isValidName ) {
532         if ( isPublished )
533           anEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
534         theObjectNames( anEntry ) = aName;
535       }
536     }
537     else {
538       do {
539         aName = aBaseName + TCollection_AsciiString(++objectCounter);
540       } while(aNameToEntry.IsBound(aName));
541       theObjectNames.Bind(anEntry, aName);
542     }
543     aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
544
545     anUpdatedScript += aName;
546     aStart = aSeq->Value(i+1) + 1;
547   }
548
549   //Add final part of the script
550   if (aLen && aSeq->Value(aLen) < aScriptLength)
551     anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
552
553   // ouv : NPAL12872
554   for (anEntryToNameIt.Initialize( theObjectNames );
555        anEntryToNameIt.More();
556        anEntryToNameIt.Next())
557   {
558     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
559     const TCollection_AsciiString& aName = anEntryToNameIt.Value();
560
561     TDF_Label L;
562     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
563     if ( L.IsNull() )
564       continue;
565
566     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
567     if ( obj.IsNull() )
568       continue;
569
570     bool anAutoColor = obj->GetAutoColor();
571     if ( anAutoColor )
572     {
573       TCollection_AsciiString aCommand( "\n\t" );
574       aCommand += aName + ".SetAutoColor(1)";
575       anUpdatedScript += aCommand.ToCString();
576     }
577
578     SALOMEDS::Color aColor = obj->GetColor();
579     if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
580     {
581       TCollection_AsciiString aCommand( "\n\t" );
582       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
583       anUpdatedScript += aCommand.ToCString();
584     }
585   }
586
587   // Make script to publish in study
588   if ( isPublished )
589   {
590     std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
591     for (anEntryToNameIt.Initialize( theObjectNames );
592          anEntryToNameIt.More();
593          anEntryToNameIt.Next())
594     {
595       const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
596       const TCollection_AsciiString& aName = anEntryToNameIt.Value();
597       if (anIgnoreObjMap.count(aEntry.ToCString()))
598         continue; // should not be dumped
599       if ( !aEntry2StEntry.IsBound( aEntry ))
600         continue; // was not published
601       TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
602
603       // find a father entry
604       const TCollection_AsciiString& aStudyEntry = aEntry2StEntry( aEntry );
605       TCollection_AsciiString aFatherStudyEntry =
606         aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
607       if ( aStEntry2Entry.IsBound( aFatherStudyEntry ))
608         aFatherEntry = aStEntry2Entry( aFatherStudyEntry );
609
610       // make a command
611       if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
612         aCommand += "addToStudyInFather( ";
613         aCommand += theObjectNames( aFatherEntry ) + ", ";
614       }
615       else
616         aCommand += "addToStudy( ";
617       if ( anEntryToBadName.IsBound( aEntry ))
618         aCommand += aName + ", \"" + anEntryToBadName( aEntry ) + "\" )";
619       else
620         aCommand += aName + ", \"" + aName + "\" )";
621
622       // bind a command to the last digit of the entry
623       int tag =
624         aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
625       anEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
626     }
627
628     // add publishing commands to the script
629     std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
630     for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
631       anUpdatedScript += (char*)anEntryToCommand->second.c_str();
632     }
633   }
634
635   anUpdatedScript += "\n\tpass\n";
636   aValidScript = true;
637
638   // fill _studyEntry2NameMap and build globalVars
639   TCollection_AsciiString globalVars;
640   _studyEntry2NameMap.Clear();
641   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
642   for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
643        aStEntryToEntryIt.More();
644        aStEntryToEntryIt.Next() )
645   {
646     const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
647     _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
648     if ( !globalVars.IsEmpty() )
649       globalVars += ", ";
650     globalVars += name;
651   }
652   if ( !globalVars.IsEmpty() ) {
653     globalVars.Insert( 1, "\n\tglobal " );
654     anUpdatedScript.Insert( posToInsertGlobalVars, globalVars );
655   }
656
657   return anUpdatedScript;
658 }
659
660 //=======================================================================
661 //function : GetDumpName
662 //purpose  :
663 //=======================================================================
664
665 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
666 {
667   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
668     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
669
670   return NULL;
671 }
672
673 //=======================================================================
674 //function : GetAllDumpNames
675 //purpose  :
676 //=======================================================================
677
678 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
679 {
680   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
681
682   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
683   for (; it.More(); it.Next()) {
684     aRetSeq->Append(it.Value());
685   }
686
687   return aRetSeq;
688 }
689
690
691 //===========================================================================
692 //                     Internal functions
693 //===========================================================================
694 void ProcessFunction(Handle(GEOM_Function)&   theFunction,
695                      TCollection_AsciiString& theScript,
696                      TDF_LabelMap&            theProcessed,
697                      std::set<std::string>&   theIgnoreObjs)
698 {
699   if (theFunction.IsNull()) return;
700
701   if (theProcessed.Contains(theFunction->GetEntry())) return;
702
703   // pass functions, that depends on nonexisting ones
704   bool doNotProcess = false;
705   TDF_LabelSequence aSeq;
706   theFunction->GetDependency(aSeq);
707   Standard_Integer aLen = aSeq.Length();
708   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
709     TDF_Label aRefLabel = aSeq.Value(i);
710     Handle(TDF_Reference) aRef;
711     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
712       doNotProcess = true;
713     }
714     else {
715       if (aRef.IsNull() || aRef->Get().IsNull()) {
716         doNotProcess = true;
717       }
718       else {
719         Handle(TDataStd_TreeNode) aT;
720         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
721           doNotProcess = true;
722         }
723         else {
724           TDF_Label aDepLabel = aT->Label();
725           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
726
727           if (aFunction.IsNull()) doNotProcess = true;
728           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
729         }
730       }
731     }
732   }
733
734   if (doNotProcess) {
735     TCollection_AsciiString anObjEntry;
736     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
737     theIgnoreObjs.insert(anObjEntry.ToCString());
738     return;
739   }
740   theProcessed.Add(theFunction->GetEntry());
741
742   TCollection_AsciiString aDescr = theFunction->GetDescription();
743   if(aDescr.Length() == 0) return;
744
745   //Check if its internal function which doesn't requires dumping
746   if(aDescr == "None") return;
747
748   theScript += "\n\t";
749   theScript += aDescr;
750 }
751
752 //=============================================================================
753 /*!
754  *  FindEntries: Returns a sequence of start/end positions of entries in the string
755  */
756 //=============================================================================
757 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
758 {
759   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
760   Standard_Integer aLen = theString.Length();
761   Standard_Boolean isFound = Standard_False;
762
763   const char* arr = theString.ToCString();
764   Standard_Integer i = 0, j;
765
766   while(i < aLen) {
767     int c = (int)arr[i];
768     j = i+1;
769     if(c >= 48 && c <= 57) { //Is digit?
770
771       isFound = Standard_False;
772       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
773         c = (int)arr[j++];
774         if(c == 58) isFound = Standard_True;
775       }
776
777       if(isFound && arr[j-2] != 58) { // last char should be a diggit
778         aSeq->Append(i+1); // +1 because AsciiString starts from 1
779         aSeq->Append(j-1);
780       }
781     }
782
783     i = j;
784   }
785
786   return aSeq;
787 }